Grunt

NodeJS is a front-end automation tool, a command line based on NodeJS, generally used for:

① compressed files ② merged files ③ simple syntax check

Gruntfile.js

role

This file is especially critical. It usually does two things: ① read the package information ② load the plug-in, register the task, and run the task (all the external interface of the Grunt is written in this file).

composition

1. Wrapping functions

There’s nothing in this wrapper function, which means that all of our code has to go into this function, right

Module. exports = function (grunt) {// exports}

You don’t know why, you just put the code in, right

2. Project/task configuration

Read the package information and call the plug-in to configure the tasks to be performed and the functions to be implemented

The first thing we usually use in Gruntfile is the initConfig method to configure the dependency information

Grunt.initconfig ({PKG: grunt.file.readJSON('package.json'), uglify: {options: {banner: '/*! <%= pkg.file %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, build: { src: 'src/<%=pkg.file %>.js', dest: 'dest/<%= pkg.file %>.min.js' } } });

pkg: Grunt.file.readJSON (‘package.json’) will read our configuration file. And convert it to a JSON object and then we can access the data in a pkg.XXX way later on. This task configuration is really just a method interface call. The parameters are defined, but the actual function is not loaded.

3. Load the relevant plug-ins

Load in any plug-ins you need

LoadNPMTasks ('grunt-contrib-uglify'); // Load the plugin grunt.loadNPMTasks ('grunt-contrib-uglify');
4. Task registration

Register a task to execute the task you configured.

Task registration code

// Default task grunt.registerTask('default', ['uglify']);

To register a task. You registered an Uglify task in default. This is an alias name. It is the default task, and when you run a grunt in the project directory, it will execute the task registered in default.

That is, when we execute the grunt command, all of Uglify’s code will execute. We can also register other tasks, such as:

grunt.registerTask(‘compress’, [‘uglify:build’]); If we want to execute this task, we cannot just type the grunt command, we need to type the grunt compress command to execute this task, and the task of this task is the build task under uglify, that is to say, We will only perform tasks defined by build in uglify, not any other tasks defined by uglify.

Note that the task name cannot be named with the same name as the subsequent task configuration. In other words, the compress name cannot be named uglify, which would cause an error or unexpected situation

Grunt.registerTask (‘ compressJS ‘,[‘concat’,’jshint’,’uglify’]); This means that the merge, check, and compress tasks are performed in sequence.

The term literacy: task & target

A task is a task, and a target is a subtask. A task can contain multiple subtasks. As shown below.

 grunt.initConfig({
    concat: {   // task
        foo: {  // target
            src: ['a.js', 'b.js'],
            dest: 'ab.js'
        },
        foo2: {
            src: ['c.js', 'd.js'],
            dest: 'cd.js'
        }
    }
  });

Whenever you run Grunt, you can assign one or more tasks to it that tell it what you want it to do.

When this “task alias” is run, each task specified in the taskList is executed in the order in which it appears. The taskList parameter must be an array of tasks.

Task alias

grunt.registerTask(taskName, [description, ] taskList)

The following task alias example defines a ‘default’ task. If no task is specified when Grunt is run, running Grunt from the console will automatically execute the ‘jshint’, ‘qunit’, ‘concat’ and ‘uglify’ tasks. Grunt.registerTask (‘default’, [‘jshint’, ‘qunit’, ‘concat’, ‘uglify’]);

You can also specify parameters for tasks. In the following example, alias “dist” will execute both “concat” and “uglify” tasks, Example 2: Grunt. RegisterTask (‘dist’, [‘concat:dist’,]) executes ‘concat’ and ‘dist’ in turn. ‘uglify:dist’]);

The basic task

grunt.registerTask(taskName, [description, ] taskFunction)

In the console type grunt foo output, foo no args. In the console, type grunt foo:testing:1234 and print foo testing 1234.

grunt.registerTask('foo', function(arg1, arg2) { if (arguments.length === 0) { grunt.log.writeln(this.name + " " +"no args"); } else { grunt.log.writeln(this.name + " " + arg1 + " " + arg2); }});
Custom task
multitasking

grunt.registerMultiTask(taskName, [description, ] taskFunction)

Run grunt log:foo on the console and print foo:123. Run grunt log:bar and it will print bar: hello world. However, if you run Grunt via Grunt Log, it prints foo: 1,2,3, then bar: hello world, and finally baz: false

grunt.initConfig({
  log: {
    foo: [1, 2, 3],
    bar: 'hello world',
    baz: false
  }
});

grunt.registerMultiTask('log', function() {
  grunt.log.writeln(this.target + ': ' + this.data);
});

Grunt: wildcard

    • Matches any number of numbers and characters other than /

  • ? Matches a single character other than /

  • ** matches any number of characters, including /, which can contain any level of path

  • {} provides a list of or expressions separated by a comma (,)

  • ! Put it at the beginning of an expression to reverse it

For example, foo/.js will match all files with the.js extension under the foo/ folder, and foo//.js will match files with the.js extension in subdirectories at any level under the foo/ directory.

Use! To do not include a specific file, it is important to note that! Must be the first character of the path. To simplify wildcards, Grunt allows you to use arrays to represent wildcards. Grunt will install sequential processing, and the result returned will be unique.

// You can specify single files, {SRC: 'foo/this.js', dest:... } // Arrays of Files {SRC: ['foo/this.js', 'foo/that.js', 'foo/the-other.js'], dest:... } // Or you can generalize with a glob pattern: {SRC: 'foo/th*.js', dest:... } // This single node-glob pattern: {SRC: 'foo/{a,b}*.js', dest:... } // Could also be written like this: {SRC: ['foo/a*.js', 'foo/b*.js'], dest:... } // All. Js files, in foo/, in alpha order, in order of characters: {SRC: ['foo/*.js'], dest:... } // Here, bar.js is first, followed by the remaining files, in alpha order, the first is bar.js, the other files in alphabetical order: {SRC: ['foo/bar.js', 'foo/*.js'], dest: ... } // All files except for bar.js, in alpha order: {SRC: ['foo/*.js', '! Foo /bar.js'], dest:... } // All files in alpha order, but with bar.js at the end, All files in alphabetical order, bar.js at the end. {SRC: ['foo/*.js', '!foo/bar.js', 'foo/bar.js'], dest: ... } Templates may be used in filepaths or glob patterns {SRC: [' SRC /<%= basename %>.js'], dest: 'build/<%= basename %>.min.js'} // But they may also reference file lists defined elsewhere in the config, Reference definition that in the rest of the file list: {SRC: [' foo / *. Js', '< % = jshint. All. SRC % >'], dest:... }

API

grunt option

Grunt’s Option API is used to share parameters between multiple tasks and access parameters set on the command line.

grunt.initConfig({
  compass: {
    dev: {
      options: {
        /* ... */
        outputStyle: 'expanded'
      },
    },
    staging: {
      options: {
        /* ... */
        outputStyle: 'compressed'
      },
    },
  },
});
var target = grunt.option('target') || 'dev';
grunt.registerTask('deploy', ['compass:' + target]);

When you execute Grunt Deploy, your stylesheet will default to the Dev target and output easy to read CSS formatted code. If you run grunt deploy –target=staging, the staging target will be executed and output the compressed CSS.

Grunt.option can also be used in tasks as follows:

grunt.registerTask('upload', 'Upload code to specified target.', function(n) {
  var target = grunt.option('target');
  // do something useful with target here
});
grunt.registerTask('deploy', ['validate', 'upload']);

Note that the Boolean parameter can specify only the key and omit the value. For example, at the command linegrunt deploy --stagingWill make grunt.option(‘staging’) return true.

Project file transfer and collaboration

After a project is developed, it is often necessary to push it to GitHub or upload FTP. Maybe someone else will pick up your project and move on, or maybe you’ll move on to another computer.

When Xiao Ming uploaded GitHub with git, he was dumbstruck. There were more than ten million items in the folder of Node_Modules in the project, which was bigger than my project itself, so it was not convenient to upload and download.

You don’t need to upload these plugins or Grunt plugins because there is a package.json file that records the dependencies of your Grunt plugins in your project. After downloading it, just type the command NPM install under the project folder, NPM will automatically read the package.json file, and download the Grunt and related plug-ins for you. It is very convenient.

You don’t need to delete it when you upload it locally. With Git, you can use a.gitignore file to filter out the folder and disable Git tracking.

touch .gitignore //create a .gitignore file.

Grunt beginner one day Grunt integrated version 30 minutes to learn to use Grunt packaging front-end code Grunt