Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Grunt get started quickly


May 25, 2021 Grunt


Table of contents


Get started quickly

The Grunt and Grunt plug-ins are installed and managed through npm, the .js of nodes.

Grunt 0.4.x must be .js version of Node. The Node version of the odd version .js considered an unstable development version.

Before you install Grunt, make sure that the npm installed in your current environment is already up-to-date, and perform the npm update -g npm instruction to upgrade (sudo instructions may be required in some systems).

If you already have Grunt installed and need to refer to some documentation manuals now, take a look at the Gruntfile instance and how to configure the task.

Install the CLI

Still using Grunt 0.3? Check out Grunt 0.3 Notes

Before you can continue, you need to install the Grunt command line (CLI) into the global environment. You may need to use sudo (for OSX, snix, BSD, and other systems) permissions or as an administrator (for Windows environments) to execute the following commands.

npm install -g grunt-cli

After the above command is executed, the grunt command is added to your system path and can be executed later in any directory.

Note that installing grunt-cli does not mean installing Grunt! T he task of the Grunt CLI is simple: call Grunt in the same directory as Gruntfile. The benefit is that you are allowed to install multiple versions of Grunt on the same system at the same time.

This allows multiple versions of Grunt to be installed on the same machine at the same time.

How the CLI works

Each time he runs grunt, he uses the require() system provided by node to find the locally installed Grunt. It is because of this mechanism that you can run grunt in any subdirect of your project.

If you find a locally installed Grunt, the CLI loads it, passes configuration information in Gruntfile, and then performs the task you specify. To better understand how the Grunt CLI works, read the source code.

Take a copy of the existing Grunt program

Assuming that the Grunt CLI is properly installed and already has a project configured with package.json and Gruntfile files, it's easy to get Grunt to practice:

  1. Take the current directory of the command line to the root of the project.
  2. The npm install command is executed to install the library on which the project depends.
  3. Execute the grunt command.

OK, it's as simple as that. You can also list all installed Grunt tasks through the grunt--help command, but it is generally more recommended to review the project's documentation for help information.

Prepare a new Grunt project

You typically need to add two files to your project: package.json and Gruntfile.

package.json: This file is used by npm to store the metadata of the project in order to publish the item as an npm module. In this file, you can list the grunt and Grunt plug-ins on which the project depends and place them in the devDependencies configuration segment.

Gruntfile: This file is named Gruntfile .js or Gruntfile.coffee to configure or define tasks and load Grunt plug-ins. Gruntfile mentioned in this document is actually a file named Gruntfile .js Gruntfile.coffee.

package.json

Package.json should be placed in the root of the project, in the same directory as Grunfile, and should be committed with the project's source code. Running npm install in the above directory (the directory where package.json is located) will automatically install the appropriate version of the dependency based on each dependency listed in the package.json file.

Here are a few ways to create a package.json file for your project:

  • Most grunt-init templates automatically create project-specific package.json files.
  • The npm init command creates a basic package.json file.
  • Copy the following case and expand as needed, refer to this description .
{
  "name": "my-project-name",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-jshint": "~0.10.0",
    "grunt-contrib-nodeunit": "~0.4.1",
    "grunt-contrib-uglify": "~0.5.0"
  }
}

Install the Grunt and Grunt plug-ins

The easiest way to add Grunt and Grunt plug-ins to an existing package.json file is through the npm install and lt;module-gt; --save-dev command. This command is not only installed, but is also automatically added to the devDependencies configuration segment, following the tilde version range format.

For example, the following command installs the latest version of Grunt into the project directory and adds it to devDependencies:

npm install grunt --save-dev

Similarly, grunt plug-ins and other node modules can be installed in the same way. The following example is the installation of the JSHint task module:

npm install grunt-contrib-jshint --save-dev

The Grunt plug-in page can be seen in the currently available Grunt plug-ins, which can be installed and used directly in the project.

After you install the plug-in, be sure to submit the updated package.json file to the project repository.

Gruntfile

Gruntfile.js or Gruntfile.coffee files are valid JavaScript or CoffeeScript files and should be placed in your project root, at the same directory level as the stackage.json file, and joined with the project source code.

Gruntfile consists of the following parts:

  • The "wrapper" function
  • Project and task configuration
  • Load grunt plug-ins and tasks
  • Custom tasks

Gruntfile file case

In this Gruntfile listed below, the project metadata in the package.json file is imported into the Grunt configuration, and the uglify task in the grunt-contrib-uglify plug-in is configured to compress the (minify) source file and dynamically generate a file header comment based on the metadata above. When the grunt command is executed on the command line, the uglify task is executed by default.

module.exports = function(grunt) {

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

  // 加载包含 "uglify" 任务的插件。
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // 默认被执行的任务列表。
  grunt.registerTask('default', ['uglify']);

};

You've been shown the whole Gruntfile before, and we'll explain each of these in detail next.

The "wrapper" function

Each Gruntfile (and grunt plug-in) follows the same format, and the Grunt code you write must be placed within this function:

module.exports = function(grunt) {
  // Do grunt-related things in here
};

Project and task configurations

Most Grunt tasks rely on configuration data that is defined within an object and passed to the grunt.initConfig method.

In the following case, grunt.file.readJSON ('package.json') introduces JSON metadata stored in the package.json file into grunt config. Because the template string can reference any configuration property, you can specify configuration data such as file paths and file list types in this way, reducing some duplication of effort.

You can store arbitrary data in this configuration object (an object passed to the initConfig() method) as long as it does not conflict with the properties required for your task configuration, otherwise it will be ignored. I n addition, since this in itself is JavaScript, you are not limited to using JSON; If necessary, you can even programmatically generate configurations.

As with most task, the urlify task in the grunt-contrib-uglify plug-in requires that its configuration be specified in a property with the same name. Here's an example, we specify a banner option (to generate a comment at the top of the file), followed by a single uglify target called build, which compresses a js file into a target file.

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

Load Grunt plug-ins and tasks

Common tasks such as concatenation, minification, grunt-contrib-uglify, and linting have all been developed as grunt plug-ins. As long as the package is listed as a dependency (dependency) package in the package.json file and installed via npm install, it can be used as a simple command in Gruntfile:

// 加载能够提供"uglify"任务的插件。
grunt.loadNpmTasks('grunt-contrib-uglify');

Note: The grunt--help command lists all available tasks.

Custom tasks

By defining default tasks, you can have Grunt perform one or more tasks by default. I n the following case, if you do not specify a task when executing the grunt command, the urlify task will be performed. I t's the same effect as performing grunt uglify or grunt default. Any number of tasks (with parameters) can be specified in the default task list array.

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

If the task in the Grunt plug-in doesn't meet your project needs, you can also customize the task in Gruntfile. For example, a default task is customized in Gruntfile below, and he doesn't even rely on the task configuration:

module.exports = function(grunt) {

  // A very basic default task.
  grunt.registerTask('default', 'Log some stuff.', function() {
    grunt.log.write('Logging some stuff...').ok();
  });

};

Project-specific tasks do not have to be defined in Gruntfile. They can be defined in .js file and loaded by the grunt.loadTasks method.