grunt用來壓縮前端腳本

grunt做爲一個任務管理工具,提供豐富的插件和強大的自動化管理功能。須要安裝node及npm。css

主要使用到兩個文件,一個是npm的依賴配置文件package.jsonnode

{
        "name": "testGrunt",
        "version": "0.1.0",
        "description" : "ciaos test",
        "author": {
                "name" : "ciaos",
                "url" : "http://weibo.com/littley"
        },
        "dependencies": {
                "grunt": "0.4.x",
                "grunt-autoprefixer": "0.2.x",
                "grunt-contrib-clean": "0.5.x",
                "grunt-contrib-copy": "0.4.x",
                "grunt-contrib-cssmin": "0.6.x",
                "grunt-contrib-jshint": "0.6.x",
                "grunt-text-replace": "~0.3.9",
                "grunt-contrib-uglify": "0.2.x",
                "grunt-contrib-watch": "0.5.x"
        }
}

另一個是Gruntfile.jsnpm

"use strict";

module.exports = function(grunt) {

  var Cfg = {
    scripts : ["src/scripts/a.js","src/scripts/b.js"],
    stylesheets: ["src/stylesheets/*.css"]
  },
  packageJson = grunt.file.readJSON('package.json'),
  banner = '/*! * version: ' + packageJson.name + '\n * build: <%= new Date() %>\n */\n\n';

  // Project configuration.
  grunt.initConfig({
    pkg: packageJson,
    uglify: {
      options: {
        banner: banner
      },
      build: {
        src: Cfg.scripts,
        dest: 'build/application.min.js'
      }
    },
    cssmin: {
      options: {
        banner: banner
      },
      build: {
        src: Cfg.stylesheets,
        dest: 'build/application.min.css'
      }
    },
    clean: {
      build: {
        src: ['build/**']
      }
    },
    watch: {
      stylesheets: {
        files: Cfg.stylesheets,
    tasks: ['buildcss']
      },
      scripts: {
        files: Cfg.scripts,
    tasks: ['buildjs']
      }
    }
  });

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

  // Default task(s).
  grunt.registerTask('default', ['uglify', 'cssmin', 'clean']);
  grunt.registerTask('buildjs', ['uglify']);
  grunt.registerTask('buildcss', ['cssmin']);
  grunt.registerTask('buildall', ['uglify', 'cssmin']);
  grunt.registerTask('daemon', ['watch']);

};

執行grunt 和 grunt daemon(監控文件變化,實時執行任務) ...json

在Gruntfile的各個任務還能添加自定義的js函數實現更多的功能。Grunt也提供豐富的api實現好比任務依賴,日誌,任務終止,狀態查詢等功能。api

相關文章
相關標籤/搜索