概要
grunt を使って簡易的にWebサーバを構築するためのメモです。
前提条件
・node.js インストール済
・npm インストール済
・grunt-ci インストール済
手順
① プロジェクトフォルダを作成する。
c:\work>mkdir sample
c:\work>cd sample
c:\work\sample>
② package.json ファイルを作成する
c:\work\sample>npm init
※色々聞かれるが全てENTERで進む
③ 以下のプラグインをインストールする。
c:\work\sample>npm install --save-dev grunt
c:\work\sample>npm install --save-dev grunt-contrib-connect
c:\work\sample>npm install --save-dev grunt-contrib-watch
c:\work\sample>npm install --save-dev jit-grunt
④ gruntfile.js ファイルを作成する。
gruntfile.js'
/*global module*/
module.exports = function (grunt) {
// Automatically load required Grunt tasks
require('jit-grunt')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
},
// Webサーバ
connect: {
server: {
options: {
port: 8080,
base: 'public'
}
}
}
});
// タスク
grunt.registerTask('default', ['connect', 'watch']);
};
※ c:\work\sample\ 配下に作成
⑤ 公開用フォルダ(public)を作成
c:\work\sample>mkdir public
⑥ public フォルダに index.html ファイルを作成する
index.html
<html>
<body>
<h1>Hello Grunt Web Server !!</h1>
</body>
</html>
※ index.html は public フォルダに配置
⑦ 以下のコマンドを実行しサイトにアクセスする。
c:\work\sample>grunt
Running "connect:server" (connect) task
Started connect web server on http://localhost:8080
Running "watch" task
Waiting...
⑧ 以下の URL にアクセスする。
画面が表示されればOK!!
以上です。
補足
通常プラグインを使う場合以下のような記述をする必要がある。
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
・・・
プラグインの数分読み込む処理を追加しなくてはならないが jit-grunt プラグイン
を使うと以下の行を追加するだけで省略することができる。
require('jit-grunt')(grunt);
更に起動時の読み込みの速度も速くなるらしい。
※起動時にしか関係ないのであまり関係ないかもしれない。
注意点は jit-grunt で自動的に読み込んでくれないプラグインもあるらしい。
その場合以下のように記述すればよいらしい。
require('jit-grunt')(grunt, {
useminPrepare: 'grunt-usemin',
ngtemplates: 'grunt-angular-templates',
cdnify: 'grunt-google-cdn',
replace: 'grunt-text-replace'
});
第二引数に静的に読込むプラグインの記述を追加すればよいらしいです。
補足以上です。