Ikeq ChengIkeq Cheng

The whole problem with the world is that fools and fanatics are always so certain of themselves, but wiser people so full of doubts.

使用Grunt实现前端自动化

Nov 21, 2014Programming477 words in 2 min

在我们的日常开发中会经常执行一些重复工作,如代码合并、压缩、编译等等。Grunt是一个基于NodeJS的前端自动化工具,它有非常丰富的插件资源,能够让开发者从这些重复性的工作中解放出来~

准备工作

安装Grunt及Grunt CLI

1
$ npm install -g grunt-cli

package.json

package.json文件描述了你的项目信息,包括名称、版本号、依赖等,通过npm init命令可以快速生成package.json文件。

1
$ npm init

package.json示例

1
2
3
4
5
6
7
8
9
10
{
"name": "my-project-name",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.5",
"grunt-contrib-jshint": "~0.10.0",
"grunt-contrib-nodeunit": "~0.4.1",
"grunt-contrib-uglify": "~0.5.0"
}
}

安装插件

通过简单的npm install命令可以快速按装package.json文件中所描述的所有依赖。

1
$ npm install

独立安装可以使用npm install <module> --save-dev命令,参数--save-dev会自动将依赖追加到package.json文件。

1
$ npm install grunt-contrib-jshint --save-dev

Gruntfile.js

Gruntfile.js为配置文件,包含以下部分:

  • 出口函数
  • 项目和插件配置
  • 加载插件和任务
  • 自定义任务

出口函数

1
2
3
module.exports = function(grunt) {
// todo
};

项目和插件配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
clean: ['dist']
},
concat: {
options: {
stripBanners: true,
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
},
dist: {
src: ['src/*.js'],
dest: 'dist/<%= pkg.name %>.js',
},
},
uglify: {
build: {
src: 'dist/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});

加载插件和任务

1
2
3
$ grunt.loadNpmTasks('grunt-contrib-clean');
$ grunt.loadNpmTasks('grunt-contrib-concat');
$ grunt.loadNpmTasks('grunt-contrib-uglify');

至此,我们可以简单是使用grunt <taskname>来执行任务。

自定义任务

通过自定义任务可以让grunt一次执行多个任务

1
2
// grunt会按照数组的定义依次执行任务
grunt.registerTask('default', ['clean', 'concat', 'uglify']);

执行

1
$ grunt

Buy me a cup of milk 🥛.