Grunt是一款受欢迎的Javascript代码自动化构建工具。提供自动化的代码检测,编译,压缩等自动化构建功能。
首先需要安装Grunt-CLI,安装完成之后就可以使用grunt命令了。执行grunt命令式,会根据Gruntfile.js中配置的require()找到安装的grunt(因此配置不同路径可以找到不同版本的grunt),加载grunt并传入Gruntfile.js里的配置信息。
那什么是Gruntfile.js呢。Gruntfile.js主要负责grunt项目中的配置信息的设置,例如启动参数,注册任务等。Grunt项目还有另外一个重要的文件package.json,该文件是Json格式,配置许多版本信息,作者信息等。其中一个比较重要的是在devDependencies定义了项目要用到的依赖(任务)。基本任务一般有watch(当监测的文件发生变化时会顺序执行你指定的任务),jshint(代码检测),clean,uglify(压缩),concat(连接)。
一个完整的Gruntfile.js文件规定所有配置需写在wrapper函数内。如下:
module.exports = function(grunt) {
}
然后通过读取package.json文件读取配置信息。例子如下:
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json')
});
};
之后就可以配置一些任务信息了。z这里讲一下jshint插件的配置。
jshint: {
// define the files to lint
files: ['gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
// configure JSHint (documented at http://www.jshint.com/docs/)
options: {
// more options here if you want to override JSHint defaults
globals: {
jQuery: true,
console: true,
module: true
}
}
}
files 定义了一个将要被检测的数组,options配置了一些参数来控制检测强度(js代码规范比较宽松),具体参数去官网看。
还可以通过grunt.registerTask()自定义自己的任务。例如:
// 只需在命令行上输入"grunt",就会执行default task
grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']);
当输入grunt的时候就会默认执行default任务,也就是执行jshint,qunit,concat,uglify。
最后我们需要在Gruntfile.js里面添加Grunt插件:
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');