##再探 butterfly.js - grunt.js篇(一)javascript
####神器 grunt.jscss
久仰grunt.js
的大名,学习grunt.js
一直是我todo List
的第一位。趁着新春佳节来临之际(打酱油的日子),就来填了这个坑,完了这个心愿。 grunt.js
的强大,强大在于它拥有不少用途丰富的插件,和不一样插件之间的联动实现更牛逼的功能。 这里默认你们已经安装了npm
和会用npm install
等指令,就不详细讲了。下面讲用到grunt-contrib-watch
和grunt-contrib-connect
实现改动代码自动刷新浏览器,而不用手动按F5
或者ctrl+R
来刷新浏览器。也会将这个酷炫的测试功能应用于butterfly.js
的应用开发之中。html
grunt-contrib-watch,这个插件超级强大,基本上,我见到用grunt.js
的应用开发,没有那个不用到grunt-contrib-watch
。其功能就是:监测指定文件的改动包括:html、css、js
,当指定的文件有改动(保存后),就会触发task
。java
grunt-contrib-connect,文档上面,它给本身的定义就是一个connect web server
,因此,这是一个能够建立服务器的插件。web
建立咱们的工程目录:npm
myproject ┣app ┣butterfly ┗main ┣theme.css ┣index.html ┗index.js ┣package.json ┗Gruntfile.js
package.json
能够用npm init
来建立,或者本身建立文件。这个属于npm
基础,不了解的本身面壁。在命令行执行如下代码:json
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
模块:app
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
的配置