Grunt 用于构建项目,对于前端开发来说,grunt最好用的两个插件就是watch 和 connect ,使用watch grunt 可以获得项目中文件变化并作出反应,使用connect 可以构建站点,这样就不需要传统服务器支持了,可以用于前端开发,而且connect 有 livereload 插件可以配合watch 使用,实时刷新页面!这样只要文件变化,浏览器就自动刷新页面,就不用F5刷新页面了!方便了前端开发!
首先,配置grunt 需要node.js的支持,node.js的安装直接查看官网就好,安装好后运行node -v 查看版本信息,成功说明安装成功。
然后安装CLI , 在node 的命名行输入中,输入
npm install -g grunt-cli
-g 的目的是为了全局可用,这样cli 就只要安装一次了, 以后使用grunt 就不需要再执行这一步了。
然后进入你的项目目录的文件中,创建两个文件 一个为package.json 另一个为 Gruntfile.js ,其中package.json放入需要调用的插件,具体解释可以查看官方文档,这里我就写了用来实现自动刷新功能的部分。
package.json
{
"name": "my-project-name",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.2",
"grunt-contrib-connect": "~0.5.0",
"grunt-contrib-watch": "~0.5.3",
"grunt-concurrent": "~0.3.0",
"load-grunt-tasks": "~0.1.0",
"time-grunt": "~0.1.1"
}
}
Gruntfile.js
module.exports = function (grunt) {
// show elapsed time at the end
require('time-grunt')(grunt);
// load all grunt tasks
require('load-grunt-tasks')(grunt);
grunt.initConfig({
// configurable paths
yeoman: {
app: 'Resource' //这个是你的需要监听的文件目录
},
watch: {
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/**/*.{html,htm}', //需要监听文件的类型,这个需要根据自己的项目结构更改,只有写进去的文件才会被watch到
'<%= yeoman.app %>/**/*.js',
'<%= yeoman.app %>/**/*.css',
'<%= yeoman.app %>/**/*.{gif,jpeg,jpg,png,svg,webp}',
'<%= yeoman.app %>/data/**/*.{gif,jpeg,jpg,png,svg,webp}',
'<%= yeoman.app %>/data/**/*.html',
'<%= yeoman.app %>/data/**/**/*.html'
]
}
},
connect: {
options: {
port: 9001,
livereload: 35731,
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
open: 'http://<%= connect.options.hostname %>:<%= connect.options.port %>/你的目录/main.htm',
}
}
},
});
grunt.registerTask('serve', function () {
grunt.task.run([
'connect:livereload',
'watch'
]);
});
grunt.registerTask('default', ['server']);
};
创建这两个文件后,在文件目录内执行
npm install --save-dev
这样控制台就会自动下载package.json中需要依赖的文件了,
然后再执行grunt server 就可以使用了!每次更改项目的文件,浏览器就会自动刷新,很爽!