grunt自定义任务——合并压缩css和js

时间:2022-04-13 22:06:14

npm文档:www.npmjs.com

grunt基础教程:http://www.gruntjs.net/docs/getting-started/

  http://www.w3cplus.com/tools/grunt-tutorial-start-grunt.html
  http://www.w3cplus.com/tools/grunt-tutorial-installing-grunt.html
package配置文件
  http://blog.csdn.net/woxueliuyun/article/details/39294375

    npm install grunt@0.4.5 --save-dev//安装grunt
    npm install -g grunt-cli//全局执行cli
    npm install
    grunt --version//检测

grunt执行子任务:

grunt.initConfig({
concat: {
js:{},
css:{}
}
})

以上代码,只执行合并css,可以 grunt concat:css

一、需求

1.执行grunt——默认合并压缩js和css
2.执行grunt js——合并压缩js
3.执行grunt css——合并压缩css

二、依赖插件

1.js压缩:uglify    https://github.com/gruntjs/grunt-contrib-uglify

三、代码

[GruntFile.js]

module.exports = function(grunt) {
grunt.initConfig({
timestamp:'<%= grunt.template.today("yyyymmddHHMM") %>',
jspath:'app/js/',
csspath:'app/css/',
concat: {
js:{
options: {
separator: ';'
},
src: [
"<%= jspath %>template.js",
"<%= jspath %>returnCode.js",
],
dest: '<%= jspath %>all.<%= timestamp %>.js'
},
css:{
src: [
'<%= csspath %>manage.css',
'<%= csspath %>jqpagination.css'
],
dest: '<%= csspath %>all.<%= timestamp %>.css'
}
},
uglify: {
options: {
banner: '/*! <%= concat.js.dest %> */\n'
},
dist: {
files: {
'<%= jspath %>all.min.<%= timestamp %>.js': ['<%= concat.js.dest %>']
}
}
},
cssmin: {
minify: {
expand: true,
cwd: '<%= csspath %>',
src: 'all.<%= timestamp %>.css',
dest: '<%= csspath %>',
ext: '.min.<%= timestamp %>.css'
}
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
//自定义任务
grunt.registerTask('default', ['concat','uglify','cssmin']);//默认
grunt.registerTask('js', ['concat:js','uglify']);
grunt.registerTask('css', ['concat:css','cssmin']);
};

[pakeage.json]

{
"name": "test",
"author": "youryida",
"devDependencies": {
"grunt": "^0.4.5",
"grunt-contrib-concat": "^0.4.0",
"grunt-contrib-uglify": "^0.4.0",
"grunt-contrib-cssmin": "latest"
}
}