Webpack's brother Grunt

☀️ About the author: Hello, everyone. I'm talking yyds
🐋 Personal home page: CSDN blog yyds with words and deeds
🎁 Series column: [front end]

Grunt

1. Introduction to grunt

1.1 INTRODUCTION

Grunt gulp Webpack is the most commonly used project packaging tool at the front end

  • Chinese homepage: http://www.gruntjs.net/
  • It is a set of front-end automatic construction tools, a command-line tool based on nodeJs
  • It is a task runner, with its rich and powerful plug-ins
  • Common functions:
    • Merge file (js/css)
    • Compressed file (js/css)
    • Syntax check (js)
    • less/sass precompiling
    • Other

1.2 use

1.2.1 initial Grunt

  • Install nodejs and check the version

    node -v
    
  • Create a simple application grunt_test

    |- build----------The folder where the files generated by the build are located
    |- src------------Source folder   
        |- js---------------js Source folder
        |- css--------------css Source folder
    |- index.html-----pagefile
    |- Gruntfile.js---grunt configuration file(Pay attention to capital letters)
    |- package.json---Project package profile
        {
          "name": "grunt_test",
          "version": "1.0.0"   
        }
    
  • Global install grunt cli

    npm install -g grunt-cli 
    
  • Install grunt

    npm install grunt --save-dev
    
  • Run build project command

    grunt  //Warning: Task "default" not found
    

    There may be a version mismatch between grunt and grunt cli

    You can modify the version according to the prompt. Specify version with @ xxx

1.2.2 configuration

  • Configuration file: gruntfile js

    • This configuration file is essentially a node function type module

    • Configuration coding includes 3 steps:

      1. Initialize plug-in configuration
      2. Load plug-in task
      3. Register build task
    • Basic code:

      module.exports = function(grunt){
        // 1. Initialize plug-in configuration
        grunt.initConfig({
            //Main coding Office
        });
        // 2. Load plug-in task
        // grunt.loadNpmTasks('grunt-contrib-concat');
        // 3. Register build task
        grunt.registerTask('default', []);
      };
      
    • Command: grunt / / the prompt succeeds, but has no effect (the plug-in has not been used to define the task)

2. Introduction to grunt plug-in

2.1 Grunt plug-in

  1. Plugin list page of grunt official website http://www.gruntjs.net/plugins
  2. Plug in category:
    Plugins contributed by the grunt team: most plugins start with contrib -
    Plug ins provided by third parties: most of them do not start with contrib -

2.2 common plug-ins:

grunt-contrib-cleanPurge files (generated by packaging)
grunt-contrib-concatMerge code into one or more files
grunt-contrib-uglifyCompress js file
grunt-contrib-jshintavascript syntax error check;
grunt-contrib-cleanPurge files (generated by packaging)
grunt-contrib-cssminCompress / merge css files
grunt-contrib-htmlminCompress html file
grunt-contrib-cleanPurge files (generated by packaging)
grunt-contrib-imageminCompressed picture file (lossless)
grunt-contrib-copyCopy files and folders
grunt-contrib-watchMonitor file changes in real time and call corresponding tasks for re execution

2.3 execution

Preface: first prepare two js files

  1. Merge js: using concat plug-in
  2. Command:
 npm install grunt-contrib-concat --save-dev
  1. code:

3.1 src/js/test1.js

  (function () {
    function add(num1, num2) {
      return num1 + num2;
    }
    console.log(add(10, 20));
  })();

3.2src/js/test2.js

   (function () {
        var arr = [2,3,4].map(function (item, index) {
          return item+1;
        });
        console.log(arr);
      })();
  1. Configuration: gruntfile js
   // Configure tasks:
   concat: {
     options: { //Optional configuration
       separator: ';'   //use; Join merge
     },
     build: { //This name is arbitrary
       src:  ["src/js/*.js"],  //Which js files are merged
       dest: "build/js/built.js" //Output js file
     }
   }
    //Loading plug-ins:
      grunt.loadNpmTasks('grunt-contrib-concat');
  //Registration task:
      grunt.registerTask('default', ['concat']);
  // Command: 
      grunt concat//A build.exe will be generated under build js

5. Effect

3. Practice

3.1 compression js: using uglify plug-in

1. Download

npm install grunt-contrib-uglify --save-dev
  1. Configuration: gruntfile js
  // Configure tasks:
      pkg : grunt.file.readJSON('package.json'),
      uglify : {
        options: {  //It's not necessary
          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']
          }
        }
      }

 //Load task:
      grunt.loadNpmTasks('grunt-contrib-uglify');

// Registration task:
      grunt.registerTask('default', ['concat', 'uglify']);
  1. Command:
  grunt uglify  //A compressed js file will be generated under build

4. Effect

It should be noted here that the Grunt components are executed in order, and the uglify task can only be executed after concat
otherwise

3.2 js syntax check: use jshint plug-in

  1. Command:
 npm install grunt-contrib-jshint --save-dev
  1. Code: 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 variables cannot be used
   "undef": true,
   //Statement must be followed by a semicolon
   "asi": false,
   //Predefined global variables that are not checked
   "predef": [ "define", "BMap", "angular", "BMAP_STATUS_SUCCESS"]
 }

3... Modify Src / JS / test1 js

(function () {
  function add(num1, num2) {
    num1 = num1 + num3
    return num1 + num2;
  }
  console.log(add(10, 20));
})();
  1. Configuration: gruntfile js
    //Configure tasks:

      jshint : {
        options: {
          jshintrc : '.jshintrc' //Specify profile
        },
        build : ['Gruntfile.js', 'src/js/*.js'] //Specifies the file to check
      }
    //Load task:
      grunt.loadNpmTasks('grunt-contrib-jshint');
	// Registration task:
      grunt.registerTask('default', ['concat', 'uglify', 'jshint']);
  1. Command:
  grunt jshint  //Prompt variable undefined and statement without semicolon -- > recompile after modification

4. Summary

  • When using a plug-in, you need to download the corresponding package first
  • Find the relevant gruntfile on the official website JS configuration
  • Adjust the code according to different conditions
  • Perform related tasks

Well, that's all for this article
If you think it's good, please pay attention to it
Welcome to actively explore

Tags: Javascript Front-end

Posted by Ruzzas on Thu, 05 May 2022 03:41:22 +0300