Optimize Requirejs project (merge and Compress) "translated 100%"

Source: Internet
Author: User
Tags script tag

English Original: Optimize (concatenate and minify) Requirejs projects Tags: requirejs node. jsparticipation in Translation (1 people): Pei Baoliang

This article demonstrates how to combine and compress a Requirejs-based project. This article will use a hard tool, which includes node. js. So if you don't have node. js on hand, click here to download one.

Motivation

A lot of articles about Requirejs have been introduced. This tool can easily divide your JavaScript code into hard-to-use modules and keep your code modular and maintainable. This way, you'll get some JavaScript files that have dependencies on each other. Simply refer to a Requirejs-based script file in your HTML document, and all necessary files will be automatically referenced to this page.

However, it is a bad practice to separate all JavaScript files in a production environment. This can result in many requests (requests), even if the files are small, wasting a lot of time. You can save the load time by merging these script files to reduce the number of requests.

Another technique to save load time is to reduce the size of the files that are loaded, and relatively small files will be transferred faster. This process is known as minimization (minification), which is achieved by carefully altering the code structure of the script file without changing the shape of the Code (behavior) and the function (functionality). For example: Remove unnecessary spaces, shorten (mangling, or both) variable (variables) names and functions (methods, or called method) names, and so on. This process of merging and compressing files is called Code optimization (optimization). This method, in addition to optimizing (optimization) JavaScript files, also applies to the optimization of CSS files.

Requirejs has two main methods: define () and require (). The two methods basically have the same definition (declaration) and they all know how to load the dependencies and then execute a callback function (callback functions). Unlike require (), define () is used to store code as a named module. So the callback function for define () needs to have a return value defined as the module. These similar defined modules are known as AMD (asynchronous module definition, asynchronous modules definitions).

If you're not familiar with Requirejs or don't quite understand what I'm writing-don't worry. Here is an example of these.

Optimization of JavaScript applications

In this section I'll show you how to optimize the TODOMVC Backbone.js + Requirejs project for Addy Osmani. Since the TODOMVC project contains many TODOMVC implementations under different frameworks, I downloaded the 1.1.0 version and extracted the Backbone.js + Requirejs application. Click here to download the application and unzip the downloaded zip file. The TODO-MVC directory will be the root of our example (root path) and from now on I will refer to this directory as <root>.

Looking at the source code of <root>/index.html, you will find that it contains only a script tag (the other one is referenced when you use Internet Explorer):

Index.html code that references a script file
<data-main=src="Js/lib/require/require.js" ></script><!--[if ie]> <script src= "Js/lib/ie.js" ></script><! [endif]-->     

In fact, the entire project only needs to reference require.js this script file. If you run this project in a browser, and in the Network tab of your favorite debugging tool, you will find that the browser also loads other JavaScript files:


All script files inside the red border are automatically loaded by Requirejs.

We will use the Requirejs Optimizer (Requirejs optimizer) to optimize this project. Locate the R.js and copy it to the <root> directory, based on the downloaded description file. Jrburke's r.js is a command-line tool that can run AMD-based projects, but more importantly, it contains Requirejs optimizer allows us to merge and compress script files (scripts).

Requirejs Optimizer has many uses. Not only can it optimize a single javascript or a single CSS file, it can also optimize the entire project or just part of it, even a MultiPage application (multi-page application). It can also use a different zoom engine (minification engines) or simply nothing (no minification at all), and so on. This article is not intended to cover all the possibilities of Requirejs optimizer, and only one of its uses is shown here.

As I mentioned before, we'll use node. js to run the optimizer (optimizer). Run it with the following command (optimizer):

Run Requirejs Optimizer
$ node R.js-o <arguments>

There are two ways to pass parameters to optimizer. One is to specify parameters on the command line:

Specifying parameters on the command line
$ node R.js-o baseurl=. Name=main Out=main-built.js
Another way is to build a configuration file (relative to the execution folder) and include the specified parameters:
$ node R.js-o build.js
What to Build.js: parameters in a configuration file
({    ".",    "main",    "Main-built.js"})  
I think it's more readable to build a configuration file than to use parameters on the command line, so I'll take that way. Next we create a <root>/build.js file for the project and include the following parameters: <root>/build.js
({appdir:'./', BASEURL:'./js ', dir:'./dist ', modules: [{name: ' main '}], Fileexclusionregexp: /^ (r|build) \.js$/, op TIMIZECSS: true, paths: {jquery: Span class= "hljs-string" > ' Lib/jquery ', underscore:  ' Lib/underscore ', Backbone:  ' Lib/backbone/backbone ', backbonelocalstorage:  lib/backbone/ Backbone.localstorage ', Text:  ' Lib/require/text '}, Shim: {underscore: {exports:  ' underscore ',  ' jquery ') , exports:  ' Backbone '}, Backbonelocalstorage: {deps: [ "Backbone '], exports:  ' Store '}})         

Figuring out all the configuration items for Requirejs Optimizer is not the purpose of this article, but I want to explain (describe) the parameters I used in this article:

Parameters Description
appdir The directory of the application (that is, <root>). All files under this folder will be copied to the dir parameter labeled folder.
baseUrl relative to Appdir, represents the anchor point for locating the file (that is represents the anchor path for finding files).
dir This is an output directory, and all application files will be copied to that folder.
modules An array that contains multiple objects. Each object represents a module that will be optimized.
fileexclusionregexp Any files or folders that match this rule will not be copied to the output directory. Since we placed R.js and build.js in the application directory, we want the optimizer (optimizer) to exclude these two files. So we can set/^ (r|build) \.js$/this way.
optimizecss Requirejs optimizer automatically optimizes the CSS file under the application. This parameter controls the optimization of CSS settings. Allowable values: "None", "standard", "Standard.keeplines", "standard.keepcomments", "Standard.keepComments.keepLines".
removecombined If True, the optimizer (optimizer) will remove the merged files from the output directory. The relative directory of the
paths Module (modules).
Shim configures a script for dependencies and "browser global" egress for modules that do not use define () and set module values.

For more information about Requirejs Optimizer and more advanced applications, you can click here to see the details of all available configuration options, in addition to the information provided earlier on the page.

Now that you have the build file, you can run the optimizer (optimizer). Go to the <root> directory and execute the following command:

Run Optimizer (optimizer)
A new folder will be generated: <root>/dist. It is important to note that now <root>/dist/js/main.js contains all the files that have been merged and compressed with dependencies. In addition, &LT;ROOT&GT;/DIST/CSS/BASE.CSS has been optimized.

Run the optimized project, which looks exactly the same as before the project was not optimized. Once again, check the network traffic information for this page and you will see that only two JavaScript files are loaded.

Requirejs Optimizer reduces the script files on the server from 13 to 2 and reduces the total file size from 164KB to 58.6KB (Require.js and Main.js).

Overhead

Obviously, after the optimization, we no longer need to reference the Require.js file. Because there are no detached script files, and all dependent files have been loaded.

Nonetheless, the optimization process merges all of our scripts to generate an optimized script file that contains many define () and require () calls. Therefore, in order for the application to function properly, define () and require () must be specified and implemented somewhere in the application (that is, the files are included).

This leads to a well-known overhead: We always have some code implementations define () and require (). These codes are not part of the application, they exist only for our infrastructure considerations (infrastructure Considerations). When we develop a JavaScript library, this problem becomes particularly large. These libraries are usually small compared to requirejs, so it can be costly to include them in the library.

While I was writing this article, there was no complete solution to this overhead, but we could use almond to alleviate the problem. Almond is a very simple AMD loader that implements the Requirejs interface (API). Therefore, it can be used to replace the REQUIREJS implementation in the optimized code, and we can include almond in the project.
As a result, I'm working on an optimizer (optimizer) that will be able to optimize the Requirejs application without the overhead, but it's still a new project (in the early stages of development) so there's nothing to show about it.

Download and summary
    • Download the TODOMVC Backbone.js + Requirejs project or view it without optimization.
    • Download the optimized TODOMVC Backbone.js + Requirejs project (located under the Dist folder) or view it.

After reading this article, I'm sure you know exactly how to optimize your Requirejs application. I'll be happy to answer any questions you may have.

Good luck!
Naorye

Optimize Requirejs project (merge and Compress) "translated 100%"

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.