Use Grunt to complete Requirejs merge compression and JS file version control

Source: Internet
Author: User
Tags lua

Recently, there is a project used requirejs to solve the front-end modularity, but with more and more pages and modules, I found that I am about to hold these lovely JS files, specifically in each page to set a bunch requirejs of configuration ( baseUrl , and so on paths ).

I do not know who said, some things repeated three times, it is time to consider the automation, so I carefully pulled out of my grunt .

We have to use grunt-contrib-requirejs this plugin to implement the automation functions described above, which is based on the r.js encapsulated grunt plug-in.

Installation grunt-contrib-requirejs
--save-dev grunt-contrib-requirejs

Configuration Grantfile

First, let's take a look at the project directory

srcis a dependent file for each page

modulesAnd lib are some modules and libraries

distIs the merged compressed file

Gruntfilefirst get a list of files that need to be processed and create an empty object to install the Requirejs configuration

var files = grunt.file.expand(‘static/js/src/*.js‘);var requireOptions = {};

Then iterate over this list of files and get the name of the JS file:

files.forEach(function (file) {    var filenamelist = file.split(‘/‘); var num = filenamelist.length; var filename = filenamelist[num - 1].replace(/\.js$/,‘‘);}

Next, for each JS file to configure a task, the task name is the JS file name:

Files.foreach (function  ' STA Tic/js ', paths: {jquery:  ' Lib/jquery.min ', Lrz:  lib/ Lrz.all.bundle ', Zepto:  ' Lib/zepto.min ', Ajax:  ' Modules/ajax ', Validators:  ' modules/validators ', page:  modules/mixins/to_ Page ', dialog:  ' Modules/mixins/toggle_login_dialog ',}, Optimizeallpluginresources: true, Name:  ' src/' + filename, out:  ' static /js/dist/' + filename +  ". js '}};         

Then initialize the grunt configuration and load and register the task

grunt.initConfig({    requirejs: requireOptions})grunt.loadNpmTasks(‘grunt-contrib-requirejs‘);grunt.registerTask(‘require‘, [‘requirejs‘]);

The requirejs configuration section ends here, and at the command line grunt require you will see static/js/dist something jumping out of the directory, all merged and compressed.

In the HTML page, you only need:

<script src="static/js/require.js"></script><script src="static/js/dist/index.js"></script>

will be able to load successfully.

Increase the version number of the JS file

Browsers sometimes cache the loaded JS or CSS, and if some of your JS dependencies change, then an error can occur, and the workaround is to add the query string after the file, for examplea.js?v=dsd712sd

So how to control the version, first of all we must think new Date() of the use, but if each release to let the browser reload (although some files are not changed at all), will inevitably cause waste. The correct scenario is to generate a MD5 value from the file content as the version number, so that the hash does not change when the file is not changed.

So how to automatically solve the issue of version number, we can use asset-cache-control this grunt plugin

Install First:

--save-dev asset-cache-control

asset-cache-controlThe use of a very simple, just set up a source file, and then set the path of the HTML file can be

grunt.initConfig({    cache: {        demo: {            assetUrl: ‘js/demo.js‘,            tmp: [‘demo.html‘] } }})

Note: The HTML file needs to be introduced into thejs/demo.js

<script src=‘js/demo.js‘></script>

Then load and register the asset-cache-control plugin

grunt.loadNpmTasks(‘asset-cache-control‘);grunt.registerTask(‘cache‘, [‘cache‘]);

Then, at the command line, grunt cache you will find index.html the tag in the script query string.

<script src=‘js/demo.js?t=92e26c5d‘></script>

Tasks configured for each JS file cache :

var files = Grunt.file.expand ( ' static/js/src/*.js '); var cacheoptions ={};files.foreach ( function (file) {var filenamelist = file.split ("/); var num = filenamelist.length; var filename = filenamelist[num-1].replace (/\.js$/,asseturl:  ' static/js/dist/' + filename + files: { ' tmp ': [Filename+            

Detect changes in each file and automate tasks

To use grunt-contrib-watch this official component

In the grunt.initConfig configuration:

watch: {    files: [‘static/js/src/*.js‘,‘static/js/modules/*.js‘],    tasks: [‘requirejs‘, ‘cache‘], options: { spawn: false }}

This way, when you modify static/js/src/ and static/js/modules/ under all JS files, it will be executed requirejs and the cache task.

Full Configuration checklist
Module.exports =function (Grunt) {var files = Grunt.file.expand (' Static/js/src/*.js ');var requireoptions = {};var cacheoptions ={}; Files.foreach (function (File) {var filenamelist = File.split (‘/‘);var num = filenamelist.length;var filename = filenamelist[num-1].replace (/\.js$/,‘‘); Requireoptions[filename] = {Options: {BASEURL:' Static/js ',Paths: {Jquery:' Lib/jquery.min ',Lrz' Lib/lrz.all.bundle ',Zepto:' Lib/zepto.min ',Ajax:' Modules/ajax ',Validators:' Modules/validators ',Page' Modules/mixins/to_page ',Dialog' Modules/mixins/toggle_login_dialog ',},Optimizeallpluginresources:TrueName' src/' + filename,Out' static/js/dist/' + filename +'. js '}}; Cacheoptions[filename] = {Asseturl:' static/js/dist/' + filename +'. js ',Files: {' tmp ': [filename+'. php '}}}); Grunt.initconfig ({requirejs:requireoptions, cache:cacheoptions, watch: {files: [ ' Static/js/src/*.js ', Span class= "hljs-string" > ' static/js/modules/*.js '], tasks: [ ' cache '], options: {spawn: Span class= "Hljs-literal" >false}}); Grunt.loadnpmtasks ( ' Asset-cache-control '); Grunt.loadnpmtasks (  Grunt-contrib-requirejs '); Grunt.loadnpmtasks ( ' Grunt-contrib-watch '); Grunt.registertask (  ' Requirejs ',  ' cache ']) }; 

In addition, the browser to load a large file is much more efficient than loading n small files, so the integration of the module has also greatly improved performance.

Use Grunt to complete Requirejs merge compression and JS file version control

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.