Grunt introduction:

  • Grunt is introduced
    • Chinese homepage: www.gruntjs.net/
    • Is a set of front-end automation build tools, a command line tool based on nodeJs
    • It is a task runner, with its rich and powerful plug-ins
    • Common functions:
      • Merge files (JS/CSS)
      • Compressed file (JS/CSS)
      • Syntax checking (JS)
      • Less/SASS precompilation processing
      • The other…
  • Install nodeJS and view the version
    node -v
    Copy the code
  • Create a simple application called grunt_test
    | - build -- -- -- -- -- -- -- -- -- -- to build the generated files in the folder | - SRC -- -- -- -- -- -- -- -- -- -- -- -- source folder | js -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- js source folder | CSS -- -- -- -- -- -- -- -- -- -- -- -- -- - | - CSS source folder Index.html file -- -- -- -- -- page | - Gruntfile. Js - grunt configuration file (note that capitalize the first letter) | - package. Json - project package configuration file {" name ":" grunt_test ", "version" : "1.0.0"}Copy the code
  • Global installation grunt- CLI
    npm install -g grunt-cli 
    Copy the code
  • The installation of grunt
    npm install grunt --save-dev
    
    Copy the code
  • Run the build project command
    Grunt // Warning: Task "default" not foundCopy the code
  • Configuration file: gruntfile.js
    • This configuration file is essentially a Node function type module
    • The configuration code consists of three steps:
      1. Initialize the plug-in configuration
      2. Loading plug-in task
      3. Register the build task
    • Basic coding:
      module.exports = function(grunt){ // 1. Initialize the plug-in configuration grunt. InitConfig ({// main encoding}); LoadNpmTasks ('grunt-contrib-concat'); Grunt. RegisterTask ('default', []); };Copy the code
    • Command: grunt // prompts success, but has no effect (no plug-in defined task yet)
  • Introduction to the Grunt plug-in
    • The plugin list page on the Grunt website is www.gruntjs.net/plugins
    • Plug-in categories:
      • Plugins contributed by the Grunt team: Most of their names start in contrib-
      • Third-party provided plugins: most don’t start in contrib-
    • Common plug-ins:
      • Grunt -contrib-clean — clean files (generated by packaging)
      • Grunt -contrib-concat – merges code from multiple files into one file
      • Grunt -contrib-uglify — compress js files
      • Grunt -contrib-jshint — javascript syntax error checking;
      • Grunt -contrib-cssmin – composes/merges CSS files
      • Grunt -contrib-htmlmin – compacts HTML files
      • Grunt -contrib-imagemin – compressed image files (non-destructive)
      • Grunt -contrib-copy — copy files and folders
      • Grunt -contrib-requirejs – merges and compresses all JS module files managed by requirejs
      • Grunt -contrib-watch – monitors file changes in real time and calls corresponding tasks to perform again
  • Merge JS: Use the concat plugin
    • Command:
      npm install grunt-contrib-concat --save-dev
      Copy the code
    • Code:
      • src/js/test1.js
        (function () { function add(num1, num2) { return num1 + num2; } console.log(add(10, 20)); }) ();Copy the code
      • src/js/test2.js
        Var arr = [2,3,4]. Map (function (item, index) {return item+1; }); console.log(arr); }) ();Copy the code
    • Configuration: Gruntfile. Js
      • Configuration tasks:
        Concat: {options: {// Separator: '; '// use; SRC: [" SRC /js/*.js"], // merge which js files dest: "build/js/ build.js "// output js files}}Copy the code
      • Loading plug-ins:
        grunt.loadNpmTasks('grunt-contrib-concat');
        Copy the code
      • Registration Task:
        grunt.registerTask('default', ['concat']);
        Copy the code
      • Command:
        Grunt // generates a built-in js under buildCopy the code
  • Compressing JS: Use uglify plug-in
    • download
      npm install grunt-contrib-uglify --save-dev
      Copy the code
    • Configuration: Gruntfile. Js
      • Configuration tasks:
        PKG: grunt. File. readJSON('package.json'), uglify: {options: {// Not required banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %> */' }, build: { files: { 'build/js/built-<%=pkg.name%>-<%=pkg.version%>.min.js': ['build/js/built.js'] } } }Copy the code
      • Loading tasks:
        grunt.loadNpmTasks('grunt-contrib-uglify');
        Copy the code
      • Registration Task:
        grunt.registerTask('default', ['concat', 'uglify']);
        Copy the code
      • Command:
        Grunt // generates a compressed JS file under buildCopy the code
  • Js syntax check: use the jshint plugin
    • Command:
      npm install grunt-contrib-jshint --save-dev
      Copy the code
    • Encoding: jshintrc
      { "curly": true, "eqeqeq": true, "eqnull": true, "expr" : true, "immed": true, "newcap": true, "noempty": True, "noarg": true, "regexp": true, "browser": true, "devel": true, "node": true, "boss": false, // undefined variable "undef": // Predef: ["define", "BMap", "angular", "BMAP_STATUS_SUCCESS"]}Copy the code
    • Modify the SRC/js/test1. Js
      (function () { function add(num1, num2) { num1 = num1 + num3 return num1 + num2; } console.log(add(10, 20)); }) ();Copy the code
    • Configuration: Gruntfile. Js
      • Configuration tasks:
        Jshint: {options: {jshintrc: '.jshintrc' // specify configuration file}, build: [' gruntfile.js ', 'SRC /js/*.js'] // Specify check file}Copy the code
      • Loading tasks:
        grunt.loadNpmTasks('grunt-contrib-jshint');
        Copy the code
      • Registration Task:
        grunt.registerTask('default', ['concat', 'uglify', 'jshint']);
        Copy the code
      • Command:
        Grunt // Prompts that variables are undefined and statements are not followed by semicolons --> Recompile after modificationCopy the code
  • Use the CSSMin plug-in
    • Installation:
      npm install grunt-contrib-cssmin --save-dev
      Copy the code
    • Code:
      • test1.css
        #box1 {
          width: 100px;
          height: 100px;
          background: red;
        }
        Copy the code
      • test2.css
        #box2 {
          width: 200px;
          height: 200px;
          background: blue;
        }
        Copy the code
      • index.html
        <link rel="stylesheet" href="build/css/output.min.css">
        <div id="box1"></div>
        <div id="box2"></div>
        Copy the code
    • Configuration: Gruntfile. Js
      • Configuration tasks:
        cssmin:{
          options: {
            shorthandCompacting: false,
            roundingPrecision: -1
          },
          build: {
            files: {
                'build/css/output.min.css': ['src/css/*.css']
            }
          }
        }
        Copy the code
      • Loading tasks:
        grunt.loadNpmTasks('grunt-contrib-cssmin');
        Copy the code
      • Registration Task:
        grunt.registerTask('default', ['concat', 'uglify', 'jshint', 'cssmin']);
        Copy the code
      • Command:
        Grunt // Generate output.min.css under build/ CSS /Copy the code
  • Use the Watch plugin (truly automated)
    • Command: NPM install grunt-contrib-watch –save-dev

    • Configuration: Gruntfile. Js

      • Configuration tasks:
        watch : {
          scripts : {
            files : ['src/js/*.js', 'src/css/*.css'],
            tasks : ['concat', 'jshint', 'uglify', 'cssmin'],
            options : {spawn : false}  
          }
        }
        Copy the code
      • Loading tasks:
        grunt.loadNpmTasks('grunt-contrib-watch');
        Copy the code
      • Registration Task:
        grunt.registerTask('default', ['concat', 'uglify', 'jshint', 'watch']); RegisterTask ('myWatch', ['default','watch']);Copy the code
      • Command:
        Grunt // The console prompts that watch has started listening, and automatically compiles and processes the changes after saving themCopy the code

Gruntfile.js file configuration

module.exports = function (grunt) { // 1. Initialize the plug-in configuration. Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: '; ', }, dist: { src: ['src/js/*.js'], dest: 'dist/js/build.js', }, }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, build: { files: { 'build/js/build.min.js': ['build/js/build.js']}}}, jshint: {options: {jshintrc: '.jshintrc' // specify configuration file}, build: ['build/js/build.min.js', 'SRC /js/*.js'] // Specify the file to check}, cssmin: {options: {mergeIntoShorthands: false, roundingPrecision: -1 }, build: { files: { 'build/css/build.min.css': ['src/css/*.css'] } } }, watch: { scripts: { files: ['src/js/*.js', 'src/css/*.css'], tasks: ['concat', 'uglify', 'jshint', 'cssmin'], options: { spawn: False, // Variable update. True Full update. }},}}); // 2. Load the plug-in task. Load the plug-in that contains the "Uglify" task. grunt.loadNpmTasks('grunt-contrib-concat'); / / merge grunt. LoadNpmTasks (' grunt - contrib - uglify '); / / compression of grunt. LoadNpmTasks (' grunt - contrib - jshint '); / / js check grunt. LoadNpmTasks (' grunt - contrib - cssmin '); // Compress/merge CSS file grunt. LoadNpmTasks ('grunt-contrib-watch'); 3. Register the build task. A list of tasks that are executed by default. The tasks executed are synchronous (sequential) grunt. RegisterTask ('default', ['concat', 'uglify', 'jshint', 'csSMin ']); grunt.registerTask('myWatch', ['default', 'watch']) };Copy the code