grunt-contrib-jshint を利用すると JSHint を使ったコードチェックを行うことができます。
npm install grunt-contrib-jshint --save-dev
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
}
Gruntfile.js
と src
, test
フォルダの下にある *.js
ファイルを対象にしてコードチェックを行う以下のコマンドを実行する
grunt jshint
grunt-contrib-watch を利用するとファイルの変更をトリガーにしてタスクを起動することができます。
以下のように grunt-contrib-watch
をインストールする
npm install grunt-contrib-watch --save-dev
この例では、grunt-contrib-jshint
を使用するため、
もしまだインストールしていない場合は、インストールする
npm install grunt-contrib-jshint --save-dev
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['gruntfile.js', 'src/**/*.js', 'test/**/*.js']
},
watch: {
files: ['gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
tasks: ['jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
};
files
には変更監視対象のファイルを記述する。
この設定では、src
, test
フォルダの下の *.js
ファイルの修正を監視するtasks
には変更時に実行するタスクを指定する。
この設定では JSHint を実行している。
複数のタスクを指定することも可能grunt watch
で起動する
grunt watch
*.js
ファイルを修正して、タスクが自動実行されることを確認する
grunt-contrib-connect を利用すると Web サーバを起動することができます。
以下のように grunt-contrib-connect
をインストールする
npm install grunt-contrib-connect --save-dev
Gruntfile.js に以下のように記述する
module.exports = function(grunt) {
grunt.initConfig({
connect: {
target1: {
options: {
hostname: 'localhost',
port: 9898,
base: 'dist',
keepalive: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-connect');
};
hostname
でサーバが利用するホスト名を指定するport
でサーバのポート番号を指定するbase
で html ファイルを格納したフォルダを指定するkeepalive: true
を指定しない場合、Gruntのタスク終了時にサーバも停止するdist
フォルダに以下のような HTML ファイルを index.html
という名前で作成する
<html>
<body>hello</body>
</html>
grunt connect
でWebサーバを起動する
grunt connect
ブラウザで http://localhost:9898 にアクセスする
以下のように open: ture
をオプションに指定すると、
サーバ起動時にブラウザも自動起動する
module.exports = function(grunt) {
grunt.initConfig({
connect: {
target1: {
options: {
hostname: 'localhost',
port: 9898,
base: 'dist',
keepalive: true,
open: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-connect');
};
grunt-contrib-connect と
grunt-contrib-watch
の livereload
オプションを設定すると、
「HTMLファイルやJavaScriptファイルを修正すると同時にブラウザのリロードを行う」
ということができるようになります。
npm install grunt-contrib-connect --save-dev
npm install grunt-contrib-watch --save-dev
module.exports = function(grunt) {
grunt.initConfig({
connect: {
server: {
options: {
hostname: 'localhost', port: 9898, base: 'dist', open: true,
livereload: 35730
}
}
},
watch: {
files: ['dist/**/*.html'],
options: {
livereload: '<%= connect.server.options.livereload %>'
}
}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['connect', 'watch']);
};
dist
フォルダに以下のような HTML ファイルを index.html
という名前で作成する
<html>
<body>hello</body>
</html>
grunt
コマンドを実行する (ブラウザに index.html の内容が表示される)
grunt
テキストエディタで index.html ファイルの内容を修正して保存し、 ブラウザのリロードが自動的に行われることを確認する