Home > Web Front-end > JS Tutorial > Getting started with Grunt (automatic task runner)_javascript skills

Getting started with Grunt (automatic task runner)_javascript skills

WBOY
Release: 2016-05-16 15:46:42
Original
1435 people have browsed it

During the development process of Javascript, you often encounter some repetitive tasks, such as merging files, compressing code, checking for grammatical errors, converting Sass code into CSS code, etc. Usually, we need to use different tools to complete different tasks, which is repetitive work and very time-consuming. Grunt is a tool invented to solve this problem, which can help us automatically manage and run various tasks.

To put it simply, Grunt is an automatic task runner that automatically runs a series of tasks in a preset order. This streamlines workflow and reduces the burden of repetitive tasks.



## Install


Grunt is based on Node.js. Before installation, you must install Node.js first, and then run the following command.


sudo npm install grunt-cli -g
Copy after login


grunt-cli indicates that the grunt command line interface is installed, and the parameter g indicates global installation.

Grunt uses a module structure. In addition to installing the command line interface, you must also install corresponding modules as needed. These modules should be installed locally, since different projects may require different versions of the same module.

First, create a text file package.json in the root directory of the project to specify the modules required by the current project. Here's an example.


{ “name”: “my-project-name”, “version”: “0.1.0”, “author”: “Your Name”, “devDependencies”: { “grunt”: “0.x.x”, “grunt-contrib-jshint”: “<em>“, “grunt-contrib-concat”: “~0.1.1”, “grunt-contrib-uglify”: “~0.1.0”, “grunt-contrib-watch”: “~0.1.4” } }</em>
Copy after login


In the above package.json file, in addition to indicating the name and version of the project, the grunt module and version the project depends on are also specified in the devDependencies attribute: the grunt core module is the latest version 0.x.x, and the jshint plug-in is the latest version. The concat plug-in is not lower than version 0.1.1, the uglify plug-in is not lower than version 0.1.0, and the watch plug-in is not lower than version 0.1.4.

Then, run the following command in the root directory of the project, and these plug-ins will be automatically installed in the node_modules subdirectory.


npm install
Copy after login


The above method is for the situation where package.json already exists. If you want to automatically generate the package.json file, you can use the npm init command and follow the on-screen prompts to answer the name and version of the required module.


npm init
Copy after login


If the existing package.json file does not include the Grunt module, you can add the --save-dev parameter when installing the Grunt module directly, and the module will be automatically added to the package.json file.


npm install <module> —save-dev
Copy after login


For example, corresponding to the module specified in the package.json file above, you need to run the following npm command.


npm install grunt —save-dev npm install grunt-contrib-jshint —save-dev npm install grunt-contrib-concat —save-dev npm install grunt-contrib-uglify —save-dev npm install grunt-contrib-watch —save-dev
Copy after login




## Command script file Gruntfile.js


After the module is installed, the next step is to create a new script file Gruntfile.js in the root directory of the project. It is a configuration file for grunt, just like package.json is a configuration file for npm. Gruntfile.js is how a general Node.js module is written.


module.exports = function(grunt) { // 配置Grunt各种模块的参数 grunt.initConfig({ jshint: { / jshint的参数 <em>/ }, concat: { /</em> concat的参数 <em>/ }, uglify: { /</em> uglify的参数 <em>/ }, watch: { /</em> watch的参数 <em>/ } }); // 从node_modules目录加载模块文件 grunt.loadNpmTasks(‘grunt-contrib-jshint'); grunt.loadNpmTasks(‘grunt-contrib-concat'); grunt.loadNpmTasks(‘grunt-contrib-uglify'); grunt.loadNpmTasks(‘grunt-contrib-watch'); // 每行registerTask定义一个任务 grunt.registerTask(‘default', [‘jshint', ‘concat', ‘uglify']); grunt.registerTask(‘check', [‘jshint']); };</em>
Copy after login


The above code uses three methods of grunt code: grunt.initConfig: defines the parameters of various modules, and each member item corresponds to a module with the same name.
grunt.loadNpmTasks: Load the modules required to complete the task. grunt.registerTask: Define specific tasks. The first parameter is the task name, and the second parameter is an array indicating the modules that the task needs to use in sequence. The default task name indicates the module to be called (jshint, concat and uglify in this example) if the grunt command is entered directly without any parameters; the check task in this example indicates using the jshint plug-in to perform syntax checking on the code.
The above code loads a total of four modules: jshint (checking for syntax errors), concat (merging files), uglify (compressing code) and watch (automatic execution). Next, there are two ways to use it.

(1) Execute a certain module from the command line, such as


grunt jshint
Copy after login


The above code indicates running the jshint module.

(2) The command line performs a certain task. For example


grunt check
Copy after login


The above code indicates running the check task. If the operation is successful, "Done, without errors." will be displayed.

If no task name is given, just typing grunt will execute the default task.



## Gruntfile.js example: grunt-contrib-cssmin module


The following uses the cssmin module to demonstrate how to write the Gruntfile.js file. The cssmin module is used to minimize CSS files.

First, install the module in the root directory of your project.


npm install grunt-contrib-cssmin —save-dev
Copy after login


Then, create a new file Gruntfile.js.


module.exports = function(grunt) { grunt.initConfig({ cssmin: { minify: { expand: true, cwd: ‘css/‘, src: [‘<em>.css', ‘!</em>.min.css'], dest: ‘css/‘, ext: ‘.min.css' }, combine: { files: { ‘css/out.min.css': [‘css/part1.min.css', ‘css/part2.min.css'] } } } }); grunt.loadNpmTasks(‘grunt-contrib-cssmin'); grunt.registerTask(‘default', [‘cssmin:minify','cssmin:combine']); };
Copy after login


The three methods in the above code are explained in detail below, and we will look at them one by one.

(1)grunt.initConfig

The grunt.initConfig method is used for module configuration, and it accepts an object as a parameter. The members of this object correspond to the modules of the same name used. Since we are configuring the cssmin module, there is a cssmin member (property) in it.

cssmin (property) points to an object that contains multiple members. In addition to some system-set members (such as options), other customized members are called targets. A module can have multiple targets. In the above code, the cssmin module has two targets. One is "minify", which is used to compress css files; the other is "combine", which is used to merge multiple css files into one. document.

For the specific settings of each target, you need to refer to the documentation of the template. As far as cssmin is concerned, the specific meaning of the parameters of the minify target is as follows:

expand: If set to true, it means that the placeholder of the following file name (i.e., the number) must be expanded into a specific file name.
cwd: The directory where the file (input) to be processed is located. src: Indicates the file that needs to be processed. If it is in array form, each item in the array is a file name, and wildcards can be used.
dest: Indicates the processed file name or directory. ext: represents the processed file suffix name.
In addition to the above parameters, there are also some parameters that are common to all grunt modules.

filter: A function that returns a Boolean value for filtering file names. Only files with a return value of true will be processed by grunt. dot: Whether to match system files starting with a period (.).
makeBase: If set to true, only the last part of the file path will be matched. For example, a?b can match /xyz/123/acb but not /xyz/acb/123.
Regarding wildcards, the meanings are as follows:
: Matches any number of characters, excluding /. ?: Matches a single character, excluding /.
**: Matches any number of characters, including /. {}: A comma-separated list is allowed, indicating an "or" (or) relationship.
!: used at the beginning of the pattern, indicating that only non-matching cases will be returned.
For example, foo/
.js matches files under the foo directory whose names end with .js, and foo//.js matches files under the foo directory and all its subdirectories whose names end with .js. The file ending with !.css means matching all files with a suffix other than ".css".

More examples of using wildcards to set src attributes:
(2)grunt.loadNpmTasks

The grunt.loadNpmTasks method loads module files.
(3)grunt.registerTask

The grunt.registerTask method defines how to call a specific task. The "default" task means that if no parameters are provided and the grunt command is entered directly, "cssmin:minify" will be run first, and then "cssmin:combine" will be run, that is, compression will be performed first and then merged. If you only perform compression or only merge, you need to specify "module name: target name" after the grunt command.
grunt-contrib-clean: Delete files.
*
grunt-contrib-compass: Use compass to compile sass files.
*
grunt-contrib-concat: Consolidate files.
*
grunt-contrib-copy: Copy files.
*
grunt-contrib-cssmin: Compress and merge CSS files.
*
grunt-contrib-imagemin: Image compression module.
*
grunt-contrib-jshint: Check JavaScript syntax.
*
grunt-contrib-uglify: Compress and merge JavaScript files.
*
grunt-contrib-watch: Monitor file changes and take corresponding actions.
If the prefix of the module is grunt-contrib, it means that the module is maintained by the grunt development team; if the prefix is ​​grunt (such as grunt-pakmanager), it means that it is maintained by a third-party developer.

Select a few modules below to see how their configuration parameters are written, that is, how to configure each module in the grunt.initConfig method.

### grunt-contrib-jshint

jshint is used to check for syntax errors, such as whether the use of semicolons is correct, whether you forgot to write parentheses, etc. Its configuration code in the grunt.initConfig method is as follows.
/.js'] },

The above code first specifies the check item of jshint. eqeqeq means that the equality operator should be replaced by a strict equality operator, and trailing means that there should be no extra spaces at the end of the line. Then, specify the files attribute, indicating that the check target is the Gruntfile.js file and the JavaScript files in all subdirectories of the lib directory.

### grunt-contrib-concat

concat is used to merge similar files. It can not only merge JavaScript files, but also CSS files.
.js', dest : ‘js/‘ } },

上面代码中的options属性指定压缩后文件的文件头,以及sourceMap设置;target目标指定输入和输出文件。

### grunt-contrib-copy

copy模块用于复制文件与目录。


copy: { main: { src: ‘src/<em>‘, dest: ‘dest/‘, }, },</em>
Copy after login


上面代码将src子目录(只包含它下面的第一层文件和子目录),拷贝到dest子目录下面(即dest/src目录)。如果要更准确控制拷贝行为,比如只拷贝文件、不拷贝目录、不保持目录结构,可以写成下面这样:


copy: { main: { expand: true, cwd: ‘src/‘, src: ‘*‘, dest: ‘dest/‘, flatten: true, filter: ‘isFile', }, },
Copy after login

grunt-contrib-watch

watch模块用来在后台运行,监听指定事件,然后自动运行指定的任务。


watch: { scripts: { files: ‘<strong>/*.js', tasks: ‘jshint', options: { livereload: true, }, }, css: { files: ‘</strong>/<em>.sass', tasks: [‘sass'], options: { livereload: true, }, }, },</em>
Copy after login


设置好上面的代码,打开另一个进程,运行grunt watch。此后,任何的js代码变动,文件保存后就会自动运行jshint任务;任何sass文件变动,文件保存后就会自动运行sass任务。

需要注意的是,这两个任务的options参数之中,都设置了livereload,表示任务运行结束后,自动在浏览器中重载(reload)。这需要在浏览器中安装livereload插件。安装后,livereload的默认端口为localhost:35729,但是也可以用livereload: 1337的形式重设端口(localhost:1337)。

### 其他模块

下面是另外一些有用的模块。

(1)grunt-contrib-clean

该模块用于删除文件或目录。


clean: { build: { src: [“path/to/dir/one”, “path/to/dir/two”] } }
Copy after login


(2)grunt-autoprefixer

该模块用于为CSS语句加上浏览器前缀。


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


(3)grunt-contrib-connect

该模块用于在本机运行一个Web Server。


connect: { server: { options: { port: 4000, base: ‘build', hostname: ‘<em>‘ } } }</em>
Copy after login


connect模块会随着grunt运行结束而结束,为了使它一直处于运行状态,可以把它放在watch模块之前运行。因为watch模块需要手动中止,所以connect模块也就会一直运行。

(4)grunt-htmlhint

该模块用于检查HTML语法。


htmlhint: { build: { options: { ‘tag-pair': true, ‘tagname-lowercase': true, ‘attr-lowercase': true, ‘attr-value-double-quotes': true, ‘spec-char-escape': true, ‘id-unique': true, ‘head-script-disabled': true, }, src: [‘index.html'] } }
Copy after login


上面代码用于检查index.html文件:HTML标记是否配对、标记名和属性名是否小写、属性值是否包括在双引号之中、特殊字符是否转义、HTML元素的id属性是否为唯一值、head部分是否没有script标记。

(5)grunt-contrib-sass模块

该模块用于将SASS文件转为CSS文件。


sass: { build: { options: { style: ‘compressed' }, files: { ‘build/css/master.css': ‘assets/sass/master.scss' } } }
Copy after login


上面代码指定输出文件为build/css/master.css,输入文件为assets/sass/master.scss。

(6)grunt-markdown

该模块用于将markdown文档转为HTML文档。


markdown: { all: { files: [ { expand: true, src: ‘.md', dest: ‘docs/html/‘, ext: ‘.html' } ], options: { template: ‘templates/index.html', } } },
Copy after login


上面代码指定将md后缀名的文件,转为docs/html/目录下的html文件。template属性指定转换时采用的模板,模板样式如下。


<!DOCTYPE html> <html> <head> <title>Document</title> </head> <body> <div id=”main” class=”container”> <%=content%> </div> </body> </html>
Copy after login


{src: ‘foo/th<em>.js'}grunt-contrib-uglify {src: ‘foo/{a,b}</em>.js'} {src: [‘foo/a<em>.js', ‘foo/b</em>.js']}
Copy after login


至于combine目标,就只有一个files参数,表示输出文件是css子目录下的out.min.css,输入文件则是css子目录下的part1.min.css和part2.min.css。

files参数的格式可以是一个对象,也可以是一个数组。


files: { ‘dest/b.js': [‘src/bb.js', ‘src/bbb.js'], ‘dest/b1.js': [‘src/bb1.js', ‘src/bbb1.js'], }, // or files: [ {src: [‘src/aa.js', ‘src/aaa.js'], dest: ‘dest/a.js'}, {src: [‘src/aa1.js', ‘src/aaa1.js'], dest: ‘dest/a1.js'}, ],
Copy after login


如果minify目标和combine目标的属性设置有重合的部分,可以另行定义一个与minify和combine平行的options属性。


 grunt.initConfig({ cssmin: { options: { /<em> … </em>/ }, minify: { /<em> … </em>/ }, combine: { /<em> … </em>/ } } });
Copy after login


grunt # 默认情况下,先压缩后合并 grunt cssmin:minify # 只压缩不合并 grunt css:combine # 只合并不压缩
Copy after login


如果不指明目标,只是指明模块,就表示将所有目标依次运行一遍。


grunt cssmin
Copy after login




## 常用模块设置


grunt的模块已经超过了2000个,且还在快速增加。下面是一些常用的模块(按字母排序)。

*


jshint: { options: { eqeqeq: true, trailing: true }, files: [‘Gruntfile.js', ‘lib/
Copy after login
## 参考链接

同时推荐:http://www.w3cplus.com/tools/writing-awesome-build-script-grunt.html


concat: { js: { src: [‘lib/module1.js', ‘lib/module2.js', ‘lib/plugin.js'], dest: ‘dist/script.js' } css: { src: [‘style/normalize.css', ‘style/base.css', ‘style/theme.css'], dest: ‘dist/screen.css' } },
Copy after login


js目标用于合并JavaScript文件,css目标用语合并CSS文件。两者的src属性指定需要合并的文件(input),dest属性指定输出的目标文件(output)。

### grunt-contrib-uglify

uglify模块用来压缩代码,减小文件体积。


uglify: { options: { banner: bannerContent, sourceMapRoot: ‘../‘, sourceMap: ‘distrib/‘+name+'.min.js.map', sourceMapUrl: name+'.min.js.map' }, target : { expand: true, cwd: ‘js/origin', src : ‘
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template