js、css文件压缩例子-grunt

使用方法:

1.把下面两个文件放入项目根目录
2.npm install
3.grunt

配置文件:

package.json

{
  "name": "my_grunt_config",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-clean": "^0.6.0",
    "grunt-contrib-concat": "~0.5.0",
    "grunt-contrib-cssmin": "^0.10.0",
    "grunt-contrib-jshint": "~0.6.0",
    "grunt-contrib-uglify": "~0.2.2"
  }
}

Gruntfile.js

module.exports = function (grunt) {
  grunt.initConfig({
    concat: {                           //合并文件
      js: {
        src: ['src/*.js'],
        dest: 'dist/built.js'
      },
      css: {
        src: ['css/*.css'],
        dest: 'dist/built.css'
      }
    },
    uglify: {                          //压缩JS文件
      my_target:{
        files:[
        {
            expand: true,
            cwd: 'src',
            src: ['*.js', '!*.min.js'],
            dest: 'src',
            ext: '.min.js'
        }]
      }       
    },
    cssmin: {                         //压缩CSS文件
      my_target: {
        files: [{
          expand: true,
          cwd: 'css',
          src: ['*.css', '!*.min.css'],
          dest: 'css',
          ext: '.min.css'
        }]
      }
    },
    clean: {                           //清理.min.xx文件
      js: ["!src/*.js", "src/*.min.js"],
      css: ["!css/*.css", "css/*.min.css"]
    }
  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-clean');

  grunt.registerTask('default', ['clean']);   //所执行的任务
}
}

你可能感兴趣的:(grunt)