一般來說,直接使用模板作爲配置文件。
module.exports = function(grunt) { "use strict"; grunt.initConfig({ //插件配置區域 }); //加載插件任務,要使用誰就添加誰 grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-imagemin'); // 註冊任務 grunt.registerTask('default', ['cssmin', 'imagemin', 'uglify']); };
grunt.loadNpmTasks()
是加載插件任務。其實就是說,你如果要使用哪個插件的功能,請在這部分用這句代碼把插件任務添加進去。grunt.registerTask()
是註冊任務,默認有一個default。默認的意思就是說,你最後使用的時候,在目錄的命令提示符裏直接輸入grunt
便可以執行註冊的任務,相當於執行了default
這個任務。
使用自定義任務
可以註冊更多的任務命令,使用其他的命名。比如
grunt.registerTask('custom', ['cssmin', 'imagemin']);
對應使用的時候,輸入:
grunt custom
gruntfile.js例子如下:
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
less: {
// 開發環境
development: {
options: {
paths: ["css"] // @import 加載文件的路徑
},
files: {
"css/style.css": "css/style.less" // 將path/to/source.less編譯爲path/to/result.css
}
},
// 線上環境
production: {
options: {
paths: ["css"], // @import 加載文件的路徑
cleancss: true, // 壓縮css文件
modifyVars: { // 重新定義全局變量
imgPath: '"http://mycdn.com/path/to/images"',
bgColor: 'red'
}
},
files: {
"css/style.css": "css/style.less"
}
}
},
concat : {
css : {
src: ['css/*.css'],
dest:'css/asset/all.css'
}
},
cssmin: {
css: {
src:'css/asset/all.css',
dest:'css/asset/all-min.css'
}
},
//壓縮整個文件夾下的所有文件
cssminAll:{
css: {
expand: true,
//相對路徑
cwd: 'css/',
src:'*.css',
dest:'css/asset'
}
});
grunt.loadNpmTasks('grunt-contrib-less');
// 開發環境
grunt.registerTask('lessDev', ['less:development']);
// 線上環境
grunt.registerTask('lessPro', ['less:production']);
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-cssmin');
// 默認任務
grunt.registerTask('default', ['concat','cssmin']);
};