Home > Article > Web Front-end > What is JavaScript self-management
JavaScript self-management refers to Grunt task automatic management tool. Grunt can help us automatically manage and run various tasks; Grunt is an automatic task runner that will automatically run a series of tasks in a preset order. , which can streamline workflow and reduce the burden of repetitive work.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
What is JavaScript self-management, Grunt: automatic task management tool
安装命令脚本文件Gruntfile.jsGruntfile.js实例:grunt-contrib-cssmin模块常用模块设置grunt-contrib-jshintgrunt-contrib-concatgrunt-contrib-uglifygrunt-contrib-copygrunt-contrib-watch其他模块参考链接
In the development process of Javascript, we often encounter some repetitive tasks, such as merging files, compressing code, and checking Syntax errors, converting Sass code to CSS code, etc. Usually, we need to use different tools to complete different tasks, which is both repetitive and very time-consuming. Grunt is a tool invented to solve this problem, which can help us automatically manage and run various tasks.
Simply put, 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.
Installation
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
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 and 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": "*","grunt-contrib-concat": "~0.1.1","grunt-contrib-uglify": "~0.1.0","grunt-contrib-watch": "~0.1.4"}}
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 , 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
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
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--save-dev
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-devnpm install grunt-contrib-jshint --save-devnpm install grunt-contrib-concat --save-devnpm install grunt-contrib-uglify --save-devnpm install grunt-contrib-watch --save-dev命令脚本文件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的参数 */ },concat: { /* concat的参数 */ },uglify: { /* uglify的参数 */ },watch:{ /* watch的参数 */ }});// 从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']);};
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 needed 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 that if the grunt command is entered directly without any parameters, the modules called at this time (jshint, concat and uglify in this example); the check task in this example indicates using the jshint plug-in to check the code syntax.
The above code loads a total of four modules: jshint (checking syntax errors), concat (merging files), uglify (compressing code) and watch (automatic execution). Next, there are two ways to use it.
[Recommended learning: javascript advanced tutorial]
(1) Command line to execute a certain module, such as
grunt jshint
The above code indicates running the jshint module .
(2) Command line to execute a certain task. For example,
grunt check
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 the project.
npm install grunt-contrib-cssmin --save-dev
Then, create a new file Gruntfile.js.
module.exports = function(grunt) {grunt.initConfig({cssmin: {minify: {expand: true,cwd: 'css/',src: ['*.css', '!*.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']);};
The three methods in the above code are explained in detail below. Let’s look at them one by one.
(1)grunt.loadNpmTasks
grunt.loadNpmTasks method loads module files.
grunt.loadNpmTasks('grunt-contrib-cssmin');
You need to use several modules. Here you need to write several grunt.loadNpmTasks statements to load each module one by one.
如果加载模块很多,这部分会非常冗长。而且,还存在一个问题,就是凡是在这里加载的模块,也同时出现在package.json文件中。如果使用npm命令卸载模块以后,模块会自动从package.json文件中消失,但是必须手动从Gruntfile.js文件中清除,这样很不方便,一旦忘记,还会出现运行错误。这里有一个解决办法,就是安装load-grunt-tasks模块,然后在Gruntfile.js文件中,用下面的语句替代所有的grunt.loadNpmTasks语句。
require('load-grunt-tasks')(grunt);
这条语句的作用是自动分析package.json文件,自动加载所找到的grunt模块。
(2)grunt.initConfig
grunt.initConfig方法用于模块配置,它接受一个对象作为参数。该对象的成员与使用的同名模块一一对应。由于我们要配置的是cssmin模块,所以里面有一个cssmin成员(属性)。
cssmin(属性)指向一个对象,该对象又包含多个成员。除了一些系统设定的成员(比如options),其他自定义的成员称为目标(target)。一个模块可以有多个目标(target),上面代码里面,cssmin模块共有两个目标,一个是“minify”,用于压缩css文件;另一个是“combine”,用于将多个css文件合并一个文件。
每个目标的具体设置,需要参考该模板的文档。就cssmin来讲,minify目标的参数具体含义如下:
expand:如果设为true,就表示下面文件名的占位符(即*号)都要扩展成具体的文件名。cwd:需要处理的文件(input)所在的目录。src:表示需要处理的文件。如果采用数组形式,数组的每一项就是一个文件名,可以使用通配符。dest:表示处理后的文件名或所在目录。ext:表示处理后的文件后缀名。
除了上面这些参数,还有一些参数也是grunt所有模块通用的。
filter:一个返回布尔值的函数,用于过滤文件名。只有返回值为true的文件,才会被grunt处理。dot:是否匹配以点号(.)开头的系统文件。makeBase:如果设置为true,就只匹配文件路径的最后一部分。比如,a?b可以匹配/xyz/123/acb,而不匹配/xyz/acb/123。
关于通配符,含义如下:
*:匹配任意数量的字符,不包括/。?:匹配单个字符,不包括/。**:匹配任意数量的字符,包括/。{}:允许使用逗号分隔的列表,表示“or”(或)关系。!:用于模式的开头,表示只返回不匹配的情况。
比如,foo/.js匹配foo目录下面的文件名以.js结尾的文件,foo/**/.js匹配foo目录和它的所有子目录下面的文件名以.js结尾的文件,!*.css表示匹配所有后缀名不为“.css”的文件。
使用通配符设置src属性的更多例子:
{src: 'foo/th*.js'}grunt-contrib-uglify{src: 'foo/{a,b}*.js'}{src: ['foo/a*.js', 'foo/b*.js']}
至于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'],},// orfiles: [{src: ['src/aa.js', 'src/aaa.js'], dest: 'dest/a.js'},{src: ['src/aa1.js', 'src/aaa1.js'], dest: 'dest/a1.js'},],
如果minify目标和combine目标的属性设置有重合的部分,可以另行定义一个与minify和combine平行的options属性。
grunt.initConfig({cssmin: {options: { /* ... */ },minify: { /* ... */ },combine: { /* ... */ }}});
(3)grunt.registerTask
grunt.registerTask方法定义如何调用具体的任务。“default”任务表示如果不提供参数,直接输入grunt命令,则先运行“cssmin:minify”,后运行“cssmin:combine”,即先压缩再合并。如果只执行压缩,或者只执行合并,则需要在grunt命令后面指明“模块名:目标名”。
grunt # 默认情况下,先压缩后合并grunt cssmin:minify # 只压缩不合并grunt css:combine # 只合并不压缩
如果不指明目标,只是指明模块,就表示将所有目标依次运行一遍。
grunt cssmin常用模块设置
grunt的模块已经超过了2000个,且还在快速增加。下面是一些常用的模块(按字母排序)。
grunt-contrib-clean:删除文件。grunt-contrib-compass:使用compass编译sass文件。grunt-contrib-concat:合并文件。grunt-contrib-copy:复制文件。grunt-contrib-cssmin:压缩以及合并CSS文件。grunt-contrib-imagemin:图像压缩模块。grunt-contrib-jshint:检查JavaScript语法。grunt-contrib-uglify:压缩以及合并JavaScript文件。grunt-contrib-watch:监视文件变动,做出相应动作。
模块的前缀如果是grunt-contrib,就表示该模块由grunt开发团队维护;如果前缀是grunt(比如grunt-pakmanager),就表示由第三方开发者维护。
以下选几个模块,看看它们配置参数的写法,也就是说如何在grunt.initConfig方法中配置各个模块。
grunt-contrib-jshint
jshint用来检查语法错误,比如分号的使用是否正确、有没有忘记写括号等等。它在grunt.initConfig方法里面的配置代码如下。
jshint: {options: {eqeqeq: true,trailing: true},files: ['Gruntfile.js', 'lib/**/*.js']},
上面代码先指定jshint的检查项目,eqeqeq表示要用严格相等运算符取代相等运算符,trailing表示行尾不得有多余的空格。然后,指定files属性,表示检查目标是Gruntfile.js文件,以及lib目录的所有子目录下面的JavaScript文件。
grunt-contrib-concat
concat用来合并同类文件,它不仅可以合并JavaScript文件,还可以合并CSS文件。
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'}},
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 : '*.js',dest : 'js/'}},
上面代码中的options属性指定压缩后文件的文件头,以及sourceMap设置;target目标指定输入和输出文件。
grunt-contrib-copy
copy模块用于复制文件与目录。
copy: {main: {src: 'src/*',dest: 'dest/',},},
上面代码将src子目录(只包含它下面的第一层文件和子目录),拷贝到dest子目录下面(即dest/src目录)。如果要更准确控制拷贝行为,比如只拷贝文件、不拷贝目录、不保持目录结构,可以写成下面这样:
copy: {main: {expand: true,cwd: 'src/',src: '**',dest: 'dest/',flatten: true,filter: 'isFile',},},grunt-contrib-watch
watch模块用来在后台运行,监听指定事件,然后自动运行指定的任务。
watch: { scripts: {files: '**/*.js',tasks: 'jshint',options: {livereload: true,}, }, css: {files: '**/*.sass',tasks: ['sass'],options: {livereload: true,}, },},
设置好上面的代码,打开另一个进程,运行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"]}}
(2)grunt-autoprefixer
该模块用于为CSS语句加上浏览器前缀。
autoprefixer: {build: {expand: true,cwd: 'build',src: [ '**/*.css' ],dest: 'build'}},
(3)grunt-contrib-connect
该模块用于在本机运行一个Web Server。
connect: {server: {options: {port: 4000,base: 'build',hostname: '*'}}}
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']}}
上面代码用于检查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'}}}
上面代码指定输出文件为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',}}},
上面代码指定将md后缀名的文件,转为docs/html/目录下的html文件。template属性指定转换时采用的模板,模板样式如下。
Document参考链接Frederic Hemberger, A build tool for front-end projectsMária Jurčovičová, Building a JavaScript Library with Grunt.jsBen Briggs,Speed Up Your Web Development Workflow with GruntOptimizing Images With GruntSwapnil Mishra, Simplifying Chores with GruntAJ ONeal, Moving to GruntJSGrunt Documentation, Configuring tasksLandon Schropp, Writing an Awesome Build Script with GruntMike Cunsolo, Get Up And Running With GruntMatt Bailey, A Beginner’s Guide to Using Grunt With MagentoPaul Bakaus, Supercharging your Gruntfile
The above is the detailed content of What is JavaScript self-management. For more information, please follow other related articles on the PHP Chinese website!