准备工作

npm i -g grunt-cli
npm i grunt --save-dev

npm i grunt-contrib-watch --save-dev
npm i grunt-contrib-stylus --save-dev

必备文件

package.json:用于保存项目元数据。
Gruntfile.js : 用于配置或定义任务、加载 Grunt 插件。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
module.exports = function(grunt) {
// 任务配置,所有插件的配置信息
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
stylus:{
compile: {
options: {
linenos: false,
compress: false,

relativeDest: 'build',

banner: '\/** \n * <%= pkg.name %>\n * version <%= pkg.version %> \n
* author <%= pkg.author %> \n * date <%= grunt.template.today() %> \n**/\n'
},
files: {
'main.css': ['css/main.styl'],
'search.css': ['css/search.styl'],
}
}
},
// watch插件的配置信息
watch: {
files: ['css/*.styl'],
tasks: ['stylus']
}
});

// 使用插件
grunt.loadNpmTasks('grunt-contrib-stylus');
grunt.loadNpmTasks('grunt-contrib-watch');

// 在终端中输入grunt时需要做些什么
grunt.registerTask('default', ['stylus','watch']);
}

常用模块

grunt-contrib-clean:删除文件。
grunt-contrib-compass:使用compass编译sass文件。
grunt-contrib-concat:合并文件。
grunt-contrib-copy:复制文件。
grunt-contrib-cssmin:压缩以及合并CSS文件。
grunt-contrib-imagemin:图像压缩模块。
grunt-contrib-jshint:检查JavaScript语法。
grunt-contrib-uglify:压缩以及合并JavaScript文件。
grunt-contrib-watch:监视文件变动,做出相应动作。
grunt-contrib-stylus:stylus编写styl输出css。

参考资料

Grunt打造前端自动化工作流