Grunt build script using Task Manager (rpm)

Grunt is a system for building Web development, but it creates more difficult. In this tutorial, you will learn how to configure Grunt create a modern Web project. When you complete the configuration tutorial, you Gruntfilewill have:

  • Copy the files from the source directory to the target directory;
  • Delete build file;
  • Compiling Stylusfiles and add a prefix to them;
  • Compilation CoffeeScript;
  • Compression CSSand JavaScriptfile;
  • Compilation Jade;
  • When a file is modified to automatically build a source file;
  • Developers run server

Grunt has a Chinese version of the official website, if you are interested in Grunt, you can click here to view the relevant Chinese documents.

Start

If you have not started using Grunt, you need to install " Node.js " and " NPM ." You also need to enter a command in the command ends npm install -g grunt-clito install Grunt. This allows your system to use anywhere you gruntcommand your Grunt.

Create a package.jsonfile, and add the following:

{
  "name": "grunt_tutorial",
  "description": "An example of how to set up Grunt for web development.",
  "author": "Landon Schropp (http://landonschropp.com)",
  "dependencies": {
    "grunt": "0.x.x",
    "grunt-autoprefixer": "0.2.x",
    "grunt-contrib-clean": "0.5.x",
    "grunt-contrib-coffee": "0.7.x",
    "grunt-contrib-connect": "0.4.x",
    "grunt-contrib-copy": "0.4.x",
    "grunt-contrib-cssmin": "0.6.x",
    "grunt-contrib-jade": "0.8.x",
    "grunt-contrib-jshint": "0.6.x",
    "grunt-contrib-stylus": "0.8.x",
    "grunt-contrib-uglify": "0.2.x",
    "grunt-contrib-watch": "0.5.x"
  },
  "engine": "node >= 0.10"
}

This file defines your project as a NPMstatement bag and your project depends needed. Each statement has its own version number. For example, grunt-contrib-copy:"0.4.x"tell NPMinstall the latest version 0.4 grunt-contrib-copypackage. At your command to run the terminal npminstallation you need to manage plug-ins.

copy

A good script always make the source code and run separate file. Such separation allows you to modify the source file without affecting the script.

Start, you make Grunt from sourcecopying files in the directory to the builddirectory. We need to create a Gruntfile.jsfile and copy the following code into this file:

= module.exports function (Grunt) {
   // configuration tasks 
  grunt.initConfig ({ 
    Copy: { 
      Build: { 
        CWD: 'Source' , 
        the src: [ '**' ], 
        dest: 'Build' , 
        the expand: to true 
      }, 
    } 
  }); 
  // loading tasks 
  grunt.loadNpmTasks ( 'Grunt-contrib-Copy' );
   // define task 
};

Let's break it down. In Nodethe need for a module, through modules.exportsto the transfer of the function and the return value. In the Gruntfiledocument by modules.exportstelling Nodedefine Grunt configuration, and returns a function. grunt.initConfigIs a method, he takes one argument: an object's properties to configure a Grunt mission.

In Grunt configuration, you have added a copytask. This task has a sub-task, called build. In Grunt, a plurality of tasks called multitasking . For the copytask, you do not need this feature, but it still needs to have at least a sub-task.

Grunt mission is to create a sub- file array format . This format is one of a source file format to provide a method Grunt a task. cwdDirectory to the source file is relative, and srcspecify the source of similar documents. **It is a wildcard to match any documents Grunt. destGrunt is used to output the results of the task. You will set the builddirectory tells Grunt copy the contents to buildthe directory. If there is a source/index.htmlfile, the output configuration build/index.htmlfile. Finally, you set the expandparameters for the cake trueto turn on these options.

grunt.loadNpmTasks("grunt-contrib-copy")Tell Grunt from the grunt-contrib-copyloaded task package. This gives us a copycommand, you can at your command console by grunt copyallow replication command.

Clean

Now you have a buildcatalog, he is used to complete the cleantask. Then you copy the configuration to which the following:

clean: {
  build: {
    src: [ 'build' ]
  },
},

Like copy, you set a cleangoal and task configuration, cleanequipped with a srcset up build, used to remove buildthe directory.

Next use grunt.loadNpmTask("grunt-contrib-clean"), load a cleanjob that allows you to run the command terminal grunt cleancommand.

grunt.loadNpmTasks('grunt-contrib-clean');

Build

If you have a buildjob, you need to delete the old before you copy the new source file build, it is not very good, let's add a task.

// 定义任务
grunt.registerTask(
  'build', 
  'Compiles all of the assets and copies the files to the build directory.', 
  [ 'clean', 'copy' ]
);

This registerTaskmethod creates a new task. The first parameter builddefines the name of this task. The second is used to describe the task. The last parameter is an array of tasks to be run, this buildtask, run cleanthe task, and then run copythe task.

Stylus

Stylus is a CSS preprocessor language. It enhances several functions on CSS, including the addition of variables, functions and nested functions.

stylus: {
  build: {
    options: {
      linenos: true,
      compress: false
    },
    files: [{
      expand: true,
      cwd: 'source',
      src: [ '**/*.styl' ],
      dest: 'build',
      ext: '.css'
    }]
  }
},

This task is slightly different from other tasks. This is still builda sub-task, but it contains two properties: optionsand files. optionsSpecifies the behavior you want to complete the task. We added two options: compressto decide whether CSS is compressed and output linenosselector Stylus add line numbers in the source file.

filesBefore formatting documents set some parameters array. After running this task, sourceunder the directory .stylfile extension compiler output file .css.

Now stylusthe task is to export the CSS file to builda directory, there is no reason to copy files to the Stylus builddirectory anywhere. Let's modify the copyconfiguration to prevent such a thing happen.

copy: {
  build: { cwd: 'source', src: [ '**', '!**/*.styl' ], dest: 'build', expand: true },
},

In the beginning of the file path can be prevented Grunt matching patterns. Do not forget to buildadd a task stylus.

grunt.registerTask(
  'build', 
  'Compiles all of the assets and copies the files to the build directory.', 
  [ 'clean', 'copy', 'stylus' ]
);

Autoprefixer

Autoprefixer is a stunner Stylus shift after people compiled into CSS, CSS3 properties to add a prefix plugin. He is a powerful library, as Nib and Compass .

Continue to add autoprefixerconfiguration:

autoprefixer: {
  build: { expand: true, cwd: 'build', src: [ '**/*.css' ], dest: 'build' }
},

I noticed a pattern yet? This configuration is very similar to other tasks. One obvious difference is cwdand the desttwo are set build. Used autoprefixerfiles and read the output in the same directory.

And in front of the same, you need to load autoprefixertask.

grunt.loadNpmTask('grunt-autoprefixer');

Not add all of the tasks to the CSS build, create a style and add a new task will be added to the task buildin.

// 配置任务
grunt.registerTask(
  'stylesheets', 
  'Compiles the stylesheets.', 
  [ 'stylus', 'autoprefixer' ]
);

grunt.registerTask(
  'build', 
  'Compiles all of the assets and copies the files to the build directory.', 
  [ 'clean', 'copy', 'stylesheets' ]
);

CSS compression

The client load a group of large CSS file, it will actually slow down the loading time of the site. Fortunately, the grunt-contrib-cssminpackage can be compressed CSS file and merge multiple files into a single file. We begin the configuration again.

cssmin: {
  build: { files: { 'build/application.css': [ 'build/**/*.css' ] }
  }
},

Use an array of file formats, this configuration uses Grunt's file object format , several files to the specified destination. All buildthe CSS files in the output directory to compression build/application.css.

CSS compression load task package and stylesheetsadded to the task.

grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask(
  'stylesheets', 
  'Compiles the stylesheets.', 
  [ 'stylus', 'autoprefixer', 'cssmin' ]
);

CoffeeScript

CoffeeScript is a JavaScript compiler a strange language. He has a clean, nice syntax, including the class name and hide a lot less than the JavaScript side.

CoffeeScript will be added to your project is easy. First, add to the configuration:

coffee: {
  build: { expand: true, cwd: 'source', src: [ '**/*.coffee' ], dest: 'build', ext: '.js' }
},

The CoffeeScript file in the source file, change their extension .js, and outputs them to the builddirectory. Next, grunt-contrib-coffeethe package is loaded task.

grunt.loadNpmTasks('grunt-contrib-coffee');

The scriptstask is loaded into the buildtask:

grunt.registerTask(
  'scripts', 
  'Compiles the JavaScript files.', 
  [ 'coffee' ]
);

grunt.registerTask(
  'build', 
  'Compiles all of the assets and copies the files to the build directory.', 
  [ 'clean', 'copy', 'stylesheets', 'scripts' ]
);

Again, you need to add an copyextension, because CoffeeScript file is not copied to the builddirectory.

copy: {
  build: { cwd: 'source', src: [ '**', '!**/*.styl', '!**/*.coffee' ], dest: 'build', expand: true },
},

Uglify

Like cssmin, like, Uglify compressed JavaScript file and compressed into a file. Here is his configuration:

uglify: {
  build: {
    options: {
      mangle: false
    },
    files: {
      'build/application.js': [ 'build/**/*.js' ]
    }
  }
},

Under default, UglifyJS will make your script with a shorter name to replace the variable and function names. If your project code is their own and that was very handy if you want to share to another project, it will cause problems. Set false'll turn off this behavior.

Like cssmintasks, this task also need to add the file object format.

Load task package, and as scriptsthe task will uglifybe added to the task:

grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask(
  'scripts', 
  'Compiles the JavaScript files.', 
  [ 'coffee', 'uglify' ]
);

Clear up

When you run grunt build, in addition to build/application.cssand build/application.jsbeyond all other CSS and JavaScript files are hanging in the builddirectory. Since you do not need them, you can add subtasks to remove them, the following is cleanconfigured:

clean: {
  build: { src: [ 'build' ] },
  stylesheets: {
    src: [ 'build/**/*.css', '!build/application.css' ] },
  scripts: {
    src: [ 'build/**/*.js', '!build/application.js' ] },
},

When you run this task, if you do not specify which sub-tasks, Grunt will run these tasks. If you run grunt clean, will perform clean:build, clean:stylesheetsand clean:scripts. If you cleancan not delete a file, it just ignores it, this is not a problem.

Note build/application.cssand build/application.jsexcluded stylesheetsand scriptssub-tasks. You do not want to delete them, after all these efforts come to work.

When updating task, subtasks adaptation:

// define the tasks
grunt.registerTask(
  'stylesheets', 
  'Compiles the stylesheets.', 
  [ 'stylus', 'autoprefixer', 'cssmin', 'clean:stylesheets' ]
);

grunt.registerTask(
  'scripts', 
  'Compiles the JavaScript files.', 
  [ 'coffee', 'uglify', 'clean:scripts' ]
);

grunt.registerTask(
  'build', 
  'Compiles all of the assets and copies the files to the build directory.', 
  [ 'clean:build', 'copy', 'stylesheets', 'scripts' ]
);

Jade

Jade is the HTML template language. By grunt-contrib-jadethe package Jadeadded to your project:

jade: {
  compile: {
    options: {
      data: {}
    },
    files: [{
      expand: true,
      cwd: 'source',
      src: [ '**/*.jade' ],
      dest: 'build',
      ext: '.html'
    }]
  }
},

Like stylusand coffeetasks, jadeconfiguration also uses an array of files. In the optionsinner set datatarget. When Jade file compiled, the object passed to each template. This is very convenient, for example, create separate development or dynamically generated content.

And in front of the same, you need to copyadd an extension:

copy: {
  build: { cwd: 'source', src: [ '**', '!**/*.styl', '!**/*.coffee', '!**/*.jade' ], dest: 'build', expand: true },
},

Do not forget to buildadd the grunt-contrib-jadetask:

grunt.loadNpmTasks('grunt-contrib-jade');
grunt.registerTask(
  'build', 
  'Compiles all of the assets and copies the files to the build directory.', 
  [ 'clean:build', 'copy', 'stylesheets', 'scripts', 'jade' ]
);

Watch

Your Gruntfile now has been very strong, but not very good, because every time you have to go run grunt build. Use grunt-contrib-watch, you do not need every run. Let's configure one of these tasks, you will see the source code, and automatically build their changes.

watch: {
  stylesheets: { files: 'source/**/*.styl', tasks: [ 'stylesheets' ] },
  scripts: {
    files: 'source/**/*.coffee', tasks: [ 'scripts' ] },
  jade: {
    files: 'source/**/*.jade', tasks: [ 'jade' ] },
  copy: {
    files: [ 'source/**', '!source/**/*.styl', '!source/**/*.coffee', '!source/**/*.jade' ], tasks: [ 'copy' ] }
},

stylesheets, scriptsAnd jadesubtasks can be monitored Stylus, CoffeeScript and Jade file changes and run their respective mandates. In the copytest all the remaining tasks in the file and copy it to buildthe directory.

Again, you need to load Grunt mission.

grunt.loadNpmTasks('grunt-contrib-watch');

Developer Server

No Web server development environment is incomplete. grunt-contrib-connectPackage is a full-featured static file server for your project is very perfect.

connect: {
  server: { options: { port: 4000, base: 'build', hostname: '*' }
  }
},

Your host server configuration builddirectory on the 4000 port. Under default, the connection to the server on your local host is the localhost. You can set up hostnameto *access the server from anywhere.

And in front of the same, you need to add the item to the task Loads and NPM tasks.

grunt.loadNpmTasks('grunt-contrib-connect');

If you try to terminal in order to run grunt connect, the server is running, then stop immediately. This is because by default, Grunt connetthe task will not run forever, you need to learn how to fix this problem.

default

Running a single task among all the tasks, it is not perfect. defaultTasks are set as follows:

grunt.registerTask(
  'default', 
  'Watches the project for changes, automatically builds them and runs a server.', 
  [ 'build', 'connect', 'watch' ]
);

defaultRun task buildto create an initial build, and then it starts to connect to the server, it will be the last run watch, monitor file changes and rebuild. Because watchalways running, so the server has been running. Running on your console grunt, and then to http: // localhost: 4000 to view your project.

to sum up

In this tutorial we have discussed a lot, but there are many things you can do Grunt. For a complete list of plug-Grunt, you can view Grunt Plugin website .

Further reading

Sign Language Translator: whole lines for translation in accordance with the original, and slightly personal understanding of technology in the translation process. If there is wrong with the translation, please also friends, colleagues pointing. Thank you!

English original: Http://Www.Sitepoint.Com/writing-awesome-build-script-grunt/

Chinese translation: http://www.w3cplus.com/tools/writing-awesome-build-script-grunt.html

Reproduced in: https: //www.cnblogs.com/JoannaQ/p/3360454.html

Guess you like

Origin blog.csdn.net/weixin_33893473/article/details/93055816