Grunt 配置

Grunt 安装

前提条件:电脑已经配置好 Node.js 的环境。

1
$ npm install -g grunt-cli

进入工程目录,运行以下命令生成 package.json 文件:

1
$ npm init

接着输入以下命令直接安装 Grunt:

1
$ npm install --save-dev grunt

除了安装 Grunt 以外,不同的项目还需要安装不同的 Grunt 插件模块。常用模块:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ npm install --save-dev load-grunt-tasks
$ npm install --save-dev grunt-contrib-jshint
$ npm install --save-dev grunt-contrib-csslint
$ npm install --save-dev grunt-htmlhint
$ npm install --save-dev grunt-contrib-watch
$ npm install --save-dev grunt-shell
$ npm install --save-dev grunt-contrib-concat
$ npm install --save-dev grunt-contrib-clean
$ npm install --save-dev grunt-contrib-less
$ npm install --save-dev grunt-autoprefixer
$ npm install --save-dev grunt-contrib-uglify
$ npm install --save-dev grunt-contrib-cssmin
$ npm install --save-dev grunt-contrib-imagemin
$ npm install --save-dev grunt-contrib-htmlmin

或一行命令解决:

1
$ npm install --save-dev load-grunt-tasks grunt-contrib-jshint grunt-contrib-csslint grunt-htmlhint grunt-contrib-watch grunt-shell grunt-contrib-concat grunt-contrib-clean grunt-contrib-less grunt-autoprefixer grunt-contrib-uglify grunt-contrib-cssmin grunt-contrib-imagemin grunt-contrib-htmlmin

模板文件

每次都要输入这么多命令,有时候会记不住。其实我们只需要一个 package.json 文件就可以搞定:

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
{
"name": "grunt-demo",
"version": "1.0.0",
"description": "just for learn grunt.",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"grunt"
],
"author": "xLsDg",
"license": "MIT",
"devDependencies": {
"grunt": "^0.4.5",
"grunt-autoprefixer": "^3.0.3",
"grunt-contrib-clean": "^0.6.0",
"grunt-contrib-concat": "^0.5.1",
"grunt-contrib-csslint": "^0.5.0",
"grunt-contrib-cssmin": "^0.13.0",
"grunt-contrib-htmlmin": "^0.4.0",
"grunt-contrib-imagemin": "^0.9.4",
"grunt-contrib-jshint": "^0.11.2",
"grunt-contrib-less": "^1.0.1",
"grunt-contrib-uglify": "^0.9.1",
"grunt-contrib-watch": "^0.6.1",
"grunt-htmlhint": "^0.4.1",
"grunt-shell": "^1.1.2",
"load-grunt-tasks": "^3.2.0"
}
}

每次需要使用的时候,将该文件放到项目文件夹下,在终端中输入 npm install 即可自动安装相应的模块。

配置文件

安装完模块之后,还需要配置一下对应的工作参数。新建 Gruntfile.js 文件与 package.json 文件同一个目录下,内容为:

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
module.exports = function(grunt) {
var cwdDir = __dirname;

var cssSrc = cwdDir + '/less';
var cssDst = cwdDir + '/css';

var jsSrc = cwdDir + '/js/page';
var jsDst = cwdDir + '/js/dist';

var htmlSrc = cwdDir + '/views';
var htmlDst = cwdDir + '/html';

var imgSrc = cwdDir + '/img';
var imgDst = cwdDir + '/img/dist';

require('load-grunt-tasks')(grunt, {
pattern: 'grunt-*',
config: cwdDir + '/package.json',
scope: 'devDependencies'
});

grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
autoprefixer: {
options: {
browsers: [
'ie >= 8',
'ff >= 10',
'chrome >= 20',
'safari >= 7',
'opera >= 10',
'ios >= 7',
'android >= 2.3'
]
},
src: [cssDst + '/*.css']
},
clean: {
options: {
'force': false, // This overrides this task from blocking deletion of folders outside current working dir (CWD). Use with caution.
'no-write': false // Will log messages of what would happen if the task was run but doesn't actually delete the files.
},
css: {
files: [{
src: [cssDst + '/*.css']
}]
},
js: {
files: [{
src: [jsDst + '/*.js']
}]
},
html: {
files: [{
src: [htmlDst + '/*.html']
}]
}
},
concat: {
options: {
separator: ';' // Concatenated files will be joined on this string. If you're post-processing concatenated JavaScript files with a minifier, you may need to use a semicolon ';\n' as the separator.
},
css: {
src: [cssDst + '/*.css', '!' + cssDst + '/all.css'],
dest: cssDst + '/all.css',
},
js: {
src: [jsDst + '/*.js', '!' + jsDst + '/all.js'],
dest: jsDst + '/all.js',
}
},
csslint: {
options: {
'important': false,
'adjoining-classes': false,
'known-properties': false,
'box-sizing': false,
'box-model': false,
'overqualified-elements': false,
'display-property-grouping': true,
'bulletproof-font-face': true,
'compatible-vendor-prefixes': false,
'regex-selectors': true,
'errors': true,
'duplicate-background-images': true,
'duplicate-properties': true,
'empty-rules': true,
'selector-max-approaching': true,
'gradients': true,
'fallback-colors': true,
'font-sizes': false,
'font-faces': true,
'floats': false,
'star-property-hack': false,
'outline-none': false,
'import': true,
'ids': true,
'underscore-property-hack': false,
'rules-count': true,
'qualified-headings': false,
'selector-max': true,
'shorthand': true,
'text-indent': true,
'unique-headings': false,
'universal-selector': true,
'unqualified-attributes': false,
'vendor-prefix': false,
'zero-units': true,
'force': true
},
src: [cssDst + '/*.css']
},
cssmin: {
options: {
compatibility : 'ie8',
noAdvanced : true
},
target: {
files: [{
expand: true,
cwd: cssDst,
src: ['*.css', '!*.min.css'],
dest: cssDst,
ext: '.min.css'
}]
}
},
htmlmin: {
options: {
removeComments: true,
collapseWhitespace: true
},
files: [{
expand: true,
cwd: htmlDst,
src: ['*.html'],
dest: htmlDst
}]
},
imagemin: {
options: {
optimizationLevel: 3,
svgoPlugins: [{
removeViewBox: false
}],
use: []
},
files: [{
expand: true,
cwd: imgSrc,
src: ['*.{png,jpg,gif}'],
dest: imgDst
}]
},
jshint: {
options: {
'jquery': true, //检查预定义的全局变量,防止出现$未定义,该项根据实际代码修改
'bitwise': false, //不检查位运算
'browser': true, //通过浏览器内置的全局变量检测
'devel': true, //允许对调试用的alert和console.log的调用
'camelcase': true, //强制验证驼峰式命名
'curly': true, //强制使用花括号
'eqeqeq': false, //不强制使用===比较运算符
'es3': true, //兼容es3规范,针对旧版浏览器编写的代码
'esnext': false, //不使用最新的es6规范
'expr': true, //允许未赋值的函数名表达式,例如console && console.log(1)
'forin': false, //不强制过滤遍历对象继承的属性
'freeze': false, //不限制对内置对象的扩展
'immed': true, //禁止未用括号包含立即执行函数
'indent': false, //不强制缩进
'latedef': true, //禁止先调用后定义
'maxdepth': false, //不限制代码块嵌套层数
'maxparams': false, //不限制函数参数个数
'newcap': false, //不对首字母大写的函数强制使用new
'noarg': false, //不禁止对arguments.caller和arguments.callee的调用
'noempty': false, //不禁止空代码块
'nonew': false, //允许直接new实例化而不赋值给变量
'plusplus': false, //允许++和--运算符使用
'quotmark': 'single', //字符串使用单引号
'scripturl': true, //允许javascript伪协议的url
'smarttabs': false, //允许混合tab和空格缩进
'strict': false, //不强制使用es5严格模式
'sub': true, //允许用[]形式访问对象属性
'undef': true, //禁止明确未定义的变量调用,如果你的变量(myvar)是在其他文件中定义的,可以使用/*global myvar */绕过检测
'unused': false, //允许定义没用的变量,在某些函数回调中,经常出现多个参数,但不一定会用
'multistr': false, //禁止多行字符串,改用加号连接
'globals': {
'jQuery': true,
'FastClick': true,
'define': true,
'unescape': true,
'require': true,
'iScroll': true,
'host': true
}
},
src: [jsDst + '/*.js']
},
less: {
options: {
},
files: [{
expand: true,
cwd: cssSrc,
src: ['*.less'],
dest: cssDst
}]
},
uglify: {
options: {
},
files: [{
expand: true,
cwd: jsDst,
src: ['*.js', '!all.js'],
dest: jsDst
}]
},
watch: {
css: {
options: {
},
files: [cssSrc + '/*.less'],
tasks: ['clean:css', 'less', 'csslint', 'autoprefixer', 'cssmin']
},
js: {
options: {
},
files: [jsSrc + '/*.js'],
tasks: ['clean:js', 'jshint', 'uglify']
},
html: {
options: {
},
files: [htmlSrc + '/*.html'],
tasks: ['clean:html', 'htmlhint', 'htmlmin']
}
},
htmlhint: {
options: {
'tagname-lowercase': true,
'attr-lowercase': true,
'attr-value-double-quotes': true,
'attr-value-not-empty': false,
'attr-no-duplication': true,
'doctype-first': true,
'tag-pair': true,
'tag-self-close': true,
'spec-char-escape': true,
'id-unique': true,
'src-not-empty': true,
'head-script-disabled': true,
'img-alt-require': false,
'doctype-html5': true,
'id-class-value': true,
'style-disabled': false,
'space-tab-mixed-disabled': true,
'id-class-ad-disabled': true,
'href-abs-or-rel': true,
'attr-unsafe-chars': true,
'force': true
},
files: [{
expand: true,
cwd: htmlSrc,
src: ['*.html'],
dest: htmlDst
}]
},
shell: {
options: {
stderr: false
},
makeDir: {
command: 'mkdir test'
}
}
});

grunt.registerTask('default', ['build-css', 'build-js', 'build-html']);

grunt.registerTask('concat-css', ['concat:css']);
grunt.registerTask('clean-css', ['clean:css']);
grunt.registerTask('build-css', ['clean:css', 'less', 'csslint', 'autoprefixer', 'cssmin']);

grunt.registerTask('concat-js', ['concat:js']);
grunt.registerTask('clean-js', ['clean:js']);
grunt.registerTask('build-js', ['clean:js', 'jshint', 'uglify']);

grunt.registerTask('clean-html', ['clean:html']);
grunt.registerTask('build-html', ['clean:html', 'htmlhint', 'htmlmin']);
};

以上内容需根据实际项目情况修改,仅作模板参考。

参考资料

1.Grunt: 任务自动管理工具

2.三十分钟学会使用 Grunt 打包前端代码