Grunt 示例文件
在本章中,让我们使用以下插件创建一个简单的 Grunt 文件-
grunt-contrib-uglify
grunt-contrib-concat
grunt-contrib-jshint
grunt-contrib-watch
安装上述所有插件并按照以下步骤创建一个简单的
Gruntfile.js-
步骤 1-您需要创建一个
wrapper 函数,它封装了 Grunt 的配置。
module.exports = function(grunt) {};
步骤 2-初始化您的配置对象,如下所示-
步骤 3-接下来,将
package.json 文件中的项目设置读入
pkg 属性。它使我们能够引用您的
package.json 文件中的属性值。
pkg: grunt.file.readJSON('package.json')
步骤 4-接下来,您可以定义任务的配置。让我们创建我们的第一个任务
concat 来连接
src/ 文件夹中存在的所有文件,并将连接后的
.js 文件存储在
dist/ 文件夹。
concat: {
options: {
// define a string to insert between files in the concatenated output
separator: ';'
},
dist: {
// files needs to be concatenated
src: ['src/**/*.js'],
// location of the concatenated output JS file
dest: 'dist/<%= pkg.name %>.js'
}
}
步骤 5-现在,让我们创建另一个名为
uglify 的任务来缩小我们的 JavaScript。
uglify: {
options: {
// banner will be inserted at the top of the output which displays the date and time
banner: '/*! <%= pkg.name %> <%= grunt.template.today() %> */\n'
},
dist: {
files: {
'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
}
}
}
上述任务在
dist/文件夹中创建一个文件,其中包含缩小的 .js 文件。
<%= concat.dist.dest %> 将指示
uglify 缩小 concat 任务生成的文件。
步骤 6-让我们通过创建
jshint 任务来配置 JSHint 插件。
jshint: {
// define the files to lint
files: ['Gruntfile.js', 'src/**/*.js'],
// configure JSHint
options: {
// more options here if you want to override JSHint defaults
globals: {
jQuery: true,
}
}
}
上面的
jshint 任务接受一个文件数组,然后是一个选项对象。上述任务将在
Gruntfile.js 和
src/**/*.js 文件中查找任何编码违规。
步骤 7-接下来,我们有
watch 任务,它会查找任何指定文件中的更改并运行您指定的任务。
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
}
第 8 步-接下来,我们必须加载所有通过
_npm 安装的 Grunt 插件。
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
步骤 9-最后,我们必须定义
default 任务。
grunt.registerTask('default', ['jshint', 'concat', 'uglify']);
只需在命令行中输入
grunt 命令即可运行
default 任务。
这是你完整的
Gruntfile.js-
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';'
},
dist: {
src: ['src/**/*.js'],
dest: 'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today() %> */\n'
},
dist: {
files: {
'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
}
}
},
jshint: {
// define the files to lint
files: ['Gruntfile.js', 'src/**/*.js'],
// configure JSHint
options: {
// more options here if you want to override JSHint defaults
globals: {
jQuery: true,
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['jshint', 'concat', 'uglify']);
};