npm install grunt-cli -g
npm init
下面是 Grunt 项目的两个基本的文件:
devDependencies 依赖的包,可自行删减
{ "name": "myApp", "version": "0.1.0", "devDependencies": { "grunt": "0.4.2", //省事的插件,有了这个可以不用写一堆的 grunt.loadNpmTasks('xxx') //再多的任务只需要写一个 require('load-grunt-tasks')(grunt) 。 "load-grunt-tasks": "^1.0.0", //用来充当一个静态文件服务器,本身集成了 livereload 功能 "grunt-contrib-connect": "~0.9.0", //监视文件的改变,然后执行指定任务,这里用来刷新 grunt server 打开的页面 "grunt-contrib-watch" : "~0.6.1", //合并 "grunt-contrib-concat" : "~0.5.0", //压缩 "grunt-contrib-uglify" :"~0.6.0", //代码校验 "grunt-contrib-jshint" : "~0.10.0" }, }
上面pakeage.jsons注释运行前需要删除掉,这里是为了介绍插件的作用!!
运行 npm install
下载安装上面的依赖
module.exports = function (grunt) { //加载所有任务 require('load-grunt-tasks')(grunt); grunt.initConfig({ connect: { server: { options: { port: 8888, //项目主目录 base: 'myApp', //声明给 watch 监听的端口 livereload: 35729, //默认值'*',可配置为本机某个 IP,localhost 或域名 hostname: 'localhost', open : { //自动打开网页 http://localhost:8888 target : "http://localhost:8888" } } } }, watch : { livereload : { //监听前面声明的端口 35729 options : { livereload : 35729 //reload : true }, //下面文件的改变就会实时刷新网页 files : [ "./myApp/*" ] } } }); grunt.registerTask('serve', ['connect:server', 'watch']); };
如果你想让文件修改在浏览器上立即刷新的话在被监视的文件上加载此js(也有其他方案 click here!)
<script src="//localhost:35729/livereload.js"></script>
grunt-connect 还可以和 grunt-connect-proxy 结合来制作本地代理访问其他域名的 api 而不用处理跨域问题
npm install -g bower
bower init
bower install [module][#version] --save
例如:
bower install requirejs --save
module.exports = function (grunt) { ..... //追加到上面的gruntfile.js中 bower : { install : { options : { targetDir : './myApp/lib', //byComponent 按文件夹 byType按类型 layout: 'byComponent', verbose: false, cleanTargetDir: false, cleanBowerDir: false } } } ..... grunt.registerTask('bowerCopy', ['bower']) }
控制台运行 : grunt bowerCopy
依赖的文件就过去了