标签:
久仰grunt.js的大名,学习grunt.js一直是我todo List的第一位。趁着新春佳节来临之际(打酱油的日子),就来填了这个坑,完了这个心愿。
grunt.js的强大,强大在于它拥有很多用途丰富的插件,和不同插件之间的联动实现更牛逼的功能。
这里默认大家已经安装了npm和会用npm install等指令,就不详细讲了。下面讲用到grunt-contrib-watch和grunt-contrib-connect实现改动代码自动刷新浏览器,而不用手动按F5或者ctrl+R来刷新浏览器。也会将这个酷炫的测试功能应用于butterfly.js的应用开发之中。
grunt-contrib-watch,这个插件超级强大,基本上,我见到用grunt.js的应用开发,没有那个不用到grunt-contrib-watch。其功能就是:监测指定文件的改动包括:html、css、js,当指定的文件有改动(保存后),就会触发task。
grunt-contrib-connect,文档上面,它给自己的定义就是一个connect web server,所以,这是一个可以创建服务器的插件。
创建我们的工程目录:
myproject
┣app
┣butterfly
┗main
┣theme.css
┣index.html
┗index.js
┣package.json
┗Gruntfile.js
package.json可以用npm init来创建,或者自己创建文件。这个属于npm基础,不了解的自己面壁。在命令行执行以下代码:
npm install grunt --save-dev
npm install grunt-contrib-connect --save-dev
npm install grunt-contrib-watch --save-dev
上面的--save-dev是两根--的,不知道为什么被吞了一根,这三行代码,分别安装了grunt、grunt-contrib-connect、grunt-contrib-watch。
编辑Gruntfile.js,这个文件是Grunt.js的核心,所有Grunt.js执行的任务都在这里控制,Grunt.js的原始状态应该是这样的:
module.exports = function(grunt){
pkg: grunt.file.readJSON(‘package.json‘),
grunt.initConfig({
//...
});
}
先设置connect模块:
connect: {
options: {
port: 9000,
hostname: ‘localhost‘,
livereload: 35729
},
server: {
options: {
open: {target:‘http://localhost:9000/main/index.html‘},
base: [‘app‘]
}
}
}
再设置watch模块:
watch: {
livereload: {
options: {
livereload: true
},
files: [‘app/main/index.html‘,‘app/main/theme.css‘, ‘app/main/index.js‘]
}
}
最后设置task
module.exports = function(grunt){
pkg: grunt.file.readJSON(‘package.json‘),
grunt.initConfig({
connect: {
options: {
port: 9000,
hostname: ‘localhost‘,
livereload: 35729
},
server: {
options: {
open: {target:‘http://localhost:9000/main/index.html‘},
base: [‘app‘]
}
}
},
watch: {
livereload: {
options: {
livereload: true
},
files: [‘app/main/index.html‘,‘app/main/theme.css‘, ‘app/main/index.js‘] //监测文件列表
}
}
});
grunt.loadNpmTasks(‘grunt-contrib-connect‘);
grunt.loadNpmTasks(‘grunt-contrib-watch‘);
grunt.registerTask(‘default‘, [‘connect:server‘, ‘watch‘])
}
编辑完成后,在命令行输入grunt,grunt.js通过grunt-contrib-connect创建一个服务器,localhost:9000(域名和端口在options设置),执行命令后,你会发现浏览器自动打开了http://localhost:9000/main/index.html。如果没有报错,就算是大功告成了。这时候你可以改动一下index.html、theme.css或者是index.js。very good。我们解放了F5这个按钮了。
其实,这个只是grunt.js的一个小功能,grunt.js强大得很,这里先挖个坑,后续会和大家分享grunt.js的其他模块和更加详细的Gruntfile.js的配置
再探 butterfly.js - grunt.js篇(一)
标签:
原文地址:http://my.oschina.net/u/2287563/blog/378517