0%

Grunt

Grunt

  • 前端自动化构建工具,压缩,合并自动化处理,适合小项目使用
  • 相关文档

GitHub

三步

  1. 初始化配置
  2. 加载插件
  3. 注册任务

初始化配置

1
2
3
4
5
6
7
8
9
10

module.exports =function (grunt) {

grunt.initConfig({
...
...
...
})
}

加载插件

常用插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
...
...
...
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-jst');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');

注册任务

1
2
3
4
5
6
grunt.loadNpmTasks('grunt-contrib-watch');
...
...
...
grunt.registerTask('default', ['clean', 'uglify']);//注册一个默认任务,后面的参数为该任务的前置任务

完整实例

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
module.exports = (grunt) => {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: { // 任务名字,和插件对应
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' //打包后文件的版权声明
},
build: {
src: './src/**/*.js', // 要打包文件的目录和文件
dest: './build/main.min.js' //打包文件输出的位置与文件名
}
},
clean: ['./build'],
copy: {
// main:{ //将整个history目录copy到build目录下
// expand: false,
// src:'./history/**',
// dest:'./build/',
// },
logo: { //将整个history目录copy到build目录下
expand: false,
src: './src/logo.png',
dest: 'build/logo.png',
}

},
cssmin: {
options: {
mergeIntoShorthands: false,
roundingPrecision: -1
},
build: { //压缩合并css
files: {
'build/main.css': ['src/*.css']
}
}
},
htmlmin: {
dist: {
options: {
removeComments: true,
collapseWhitespace: true
},
files: {
'build/index.html': 'src/index.html',
}
}
},
connect: {
server: {
options: {
open:true, //自动打开浏览器
port: 8000,
base: './build',
hostname: '*',
// keepalive: true, //在命令行运行 grunt connect 后不会立即退出
livereload: true //和watch配合使用,需要设置 keepalive: false,
},
},
},
watch: {
scripts: {
files: ['src/*.js', 'src/*.css', 'src/*.html', 'Gruntfile.js'],
tasks: 'build',
options: {
spawn: false, //增量更新
livereload: true
}
},

},
});


grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');

// 默认被执行的任务列表。
grunt.registerTask('build', ['clean', 'cssmin', 'uglify', 'htmlmin', 'copy']);
grunt.registerTask('default', ['build', 'connect','watch']);

}