grunt 压缩多个js,css文件

付测试例子链接:http://pan.baidu.com/s/1jGk2TEm 

步骤:首先需要再与Gruntfile.js同一层创建文件夹dist,然后执行$npm install ,最后执行grunt.

看了两天的grunt各种资料,终于在今天打包成功了,我看了网上的很多资料,在打包的时候都出现很多问题,原因是我的js与css路径问题,现在做一个简单的测试例子。

首先目录结构

grunt 压缩多个js,css文件_第1张图片

package.json

{
  "name": "pro",
  "version": "0.1.1",
  "description": "最后更新于:2015-11-12",
  "main": "Gruntfile.js",
  "dependencies": {
    "is-stream": "^1.0.1",
    "lodash": "^3.10.1",
    "xtend": "^4.0.1"
  },
  "devDependencies": {
   "grunt-contrib-cssmin": "latest",
    "grunt-contrib-jshint": "latest",
    "grunt-contrib-htmlmin": "latest",
    "grunt-contrib-uglify": "latest"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "www.bluesdream.com",
  "license": "MIT license"
}

 

Gruntfile.js

module.exports = function (grunt) {

  grunt.initConfig({
      jshint: {
            all: [
                'Gruntfile.js',
                'pro/**/*.js'
            ],
            options: {
                browser: true
            }
        },
    //压缩JS
    uglify: {
      prod: {
        options: {
          compress: {
            global_defs: {
              PROD: true
            },
            dead_code: true
          }
        },

        files: [{
            expand: true,
            cwd: 'pro/js',
            src: ['*.js','**.js'],
            dest: 'dist/js'
        }]
      }
    },

    //压缩CSS
    cssmin: {
      prod: {
        options: {
          report: 'gzip'
        },
        files: [
          {
            expand: true,
            cwd: 'pro/css',
            src: ['*.css','**/*.css'],
            dest: 'dist/css'
          }
        ]
      }
    },

    //压缩HTML
    htmlmin: {
      options: {
        removeComments: true,
        removeCommentsFromCDATA: true,
        collapseWhitespace: true,
        collapseBooleanAttributes: true,
        removeAttributeQuotes: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeOptionalTags: true
      },
      html: {
        files: [
          {expand: true, cwd: 'pro', src: ['*.html','**/*.html'], dest: 'dist'}
        ]
      }
    }

  });


  grunt.loadNpmTasks('grunt-contrib-uglify');  
  grunt.loadNpmTasks('grunt-contrib-cssmin');  
  grunt.loadNpmTasks('grunt-contrib-htmlmin'); 
  grunt.loadNpmTasks('grunt-contrib-jshint');
    
  grunt.registerTask('default', ['jshint','uglify','cssmin','htmlmin']);  
};

  然后执行 $npm install ,下载依赖包

  最后执行grunt default,成功打包。

  我在打包过程中出过错,然后跑去问了grunt原作者,得到他本人的回答,表示很兴奋。他说我的包版本太旧了,让我试试最新的,我索性直接把package.json里面的包版本都设置为latest,压缩成功。

grunt 压缩多个js,css文件_第2张图片

你可能感兴趣的:(grunt 压缩多个js,css文件)