Requirejs and AMD Specifications

Source: Internet
Author: User

Original: http://www.360doc.com/content/15/0424/17/21412_465723360.shtml

Reference: JavaScript standard reference Tutorial (Alpha)

Directory
    • Overview
    • Define method: Define Module
    • Require method: Calling module
    • AMD Mode Summary
    • Configuring the Require.js:config Method
    • Plug - ins
    • Optimizer R.js
    • Reference links
Overview

Requirejs is a tool library that is used primarily for client-side module management. It allows the client's code to be separated into modules for asynchronous or dynamic loading, which improves the performance and maintainability of the code. Its module management complies with the AMD Specification (asynchronous Module Definition).

The basic idea of Requirejs is to define the code as a module through the Define method, and to implement the module loading of the code through the Require method.

First, embed require.js in a Web page, and then you can do modular programming in your Web page.

<script data-main="scripts/main" src="scripts/require.js"></script>

The Data-main property of the above code cannot be omitted to specify the script file where the main code resides, in the example above, the Main.js file under the scripts subdirectory. The user-defined code is placed in this main.js file.

Define method: Define Module

The Define method is used to define the module, and Requirejs requires each module to be placed in a separate file.

Depending on whether other modules are dependent, there are two scenarios to discuss. The first case is to define a standalone module, that is, the module defined does not depend on other modules, and the second case is to define a non-independent module, that is, the module that is defined depends on the other modules.

(1) Standalone module

If the module being defined is a standalone module, it does not need to rely on any other modules and can be generated directly using the Define method.

define({    method1: function() {},    method2: function() {},});

The above code generates a module with METHOD1, Method2 two methods.

Another equivalent notation is to write the object as a function, and the return value of the function is the module of the output.

define(function () {    return {        method1: function() {},        method2: function() {},    };});

The latter is a higher degree of freedom to write some module initialization code in the function body.

It is worth noting that the module defined by define can return any value, not limited to the object.

(2) Non-independent modules

If the module being defined relies on other modules, the Define method must take the following format.

define([‘module1‘, ‘module2‘], function(m1, m2) {   ...});

The first parameter of the Define method is an array whose members are the modules that the current module depends on. For example, [' Module1 ', ' module2 '] means that the new module we define depends on the Module1 module and the Module2 module, and the new module will work only if the two modules are loaded first. In general, the Module1 module and the Module2 module refer to the Module1.js file and the Module2.js file in the current directory, which is equivalent to writing ['./module1 ', './module2 '].

The second argument to the Define method is a function that will be called when all the members of the preceding array are loaded successfully. Its parameters correspond to the members of the array, such as function (M1, m2), which means that the first parameter of the function M1 corresponds to the Module1 module, and the second parameter m2 corresponding to the Module2 module. This function must return an object for other modules to invoke.

define([‘module1‘, ‘module2‘], function(m1, m2) {    return {        method: function() {            m1.methodA();            m2.methodB();        }    };});

The above code indicates that the new module returns an object that is called by an externally invoked interface, and the Menthod method internally invokes the MethodA method of the M1 module and the MethodB method of the M2 module.

It is important to note that the callback function must return an object that is the module you define.

If you rely on a lot of modules, the parameters corresponding to module one by one is very cumbersome.

define(    [       ‘dep1‘, ‘dep2‘, ‘dep3‘, ‘dep4‘, ‘dep5‘, ‘dep6‘, ‘dep7‘, ‘dep8‘],    function(dep1,   dep2,   dep3,   dep4,   dep5,   dep6,   dep7,   dep8){        ...    });

To avoid the tedious wording of the above code, REQUIREJS provides a simpler way to write.

define(    function (require) {        var dep1 = require(‘dep1‘),            dep2 = require(‘dep2‘),            dep3 = require(‘dep3‘),            dep4 = require(‘dep4‘),            dep5 = require(‘dep5‘),            dep6 = require(‘dep6‘),            dep7 = require(‘dep7‘),            dep8 = require(‘dep8‘);            ...    }});

Here is an example of a define practical use.

define([‘math‘, ‘graph‘],     function ( math, graph ) {        return {            plot: function(x, y){                return graph.drawPie(math.randomGrid(x,y));            }        }    };);

The modules defined above depend on the math and graph two libraries, and then return an object with a plot interface.

Another practical example is to choose to load Zepto or jquery by judging whether the browser is ie.

define((‘__proto__‘ in {} ? [‘zepto‘] : [‘jquery‘]), function($) {    return $;});

The above code defines an intermediate module, which first determines whether the browser supports the Proto property (except IE, which is supported by other browsers), and if true, loads the Zepto library or loads the jquery library.

Require method: Calling module

The Require method is used to invoke the module. Its parameters are similar to the Define method.

require([‘foo‘, ‘bar‘], function ( foo, bar ) {        foo.doSomething();});

The above method represents loading foo and bar two modules, and when all two modules are loaded successfully, execute a callback function. The callback function is used to accomplish the specific task.

The first parameter of the Require method is an array that represents a dependency. This array can be written very flexibly, see the example below.

require( [ window.JSON ? undefined : ‘util/json2‘ ], function ( JSON ) {  JSON = JSON || window.JSON;  console.log( JSON.parse( ‘{ "JSON" : "HERE" }‘ ) );});

When the code above loads the JSON module, it first determines whether the browser natively supports JSON objects. If yes, the undefined is passed into the callback function, otherwise the Json2 module under the Util directory is loaded.

The Require method can also be used inside the Define method.

define(function (require) {   var otherModule = require(‘otherModule‘);});

The following example shows how to load a module dynamically.

define(function ( require ) {    var isReady = false, foobar;     require([‘foo‘, ‘bar‘], function (foo, bar) {        isReady = true;        foobar = foo() + bar();    });     return {        isReady: isReady,        foobar: foobar    };});

The above code defines the module, the internal loading Foo and bar two modules, before the load is complete, the IsReady property value is False, after the load is completed, it becomes true. Therefore, the next action can be determined based on the value of the IsReady property.

The following example shows that the output of the module is a Promise object.

define([‘lib/Deferred‘], function( Deferred ){    var defer = new Deferred();     require([‘lib/templates/?index.html‘,‘lib/data/?stats‘],        function( template, data ){            defer.resolve({ template: template, data:data });        }    );    return defer.promise();});

The Define method of the above code returns a Promise object that can be used in the then method of the object to specify the next action.

If the server side is in JSONP mode, you can call it directly in require by specifying that the callback parameter of JSONP is define.

require( [     "http://someapi.com/foo?callback=define"], function (data) {    console.log(data);});

The Require method allows you to add a third parameter, the callback function for error handling.

require(    [ "backbone" ],     function ( Backbone ) {        return Backbone.View.extend({ /* ... */ });    },     function (err) {        // ...    });

The third parameter of the Require method, the callback function that handles the error, accepts an error object as a parameter.

The Require object also allows you to specify a listener function for the global error event. All errors that are not caught by the above method are triggered by this listener function.

requirejs.onError = function (err) {    // ...};
AMD Mode Summary

Define and require these two methods of defining modules, calling modules, collectively referred to as AMD mode. Its module-defined approach is very clear and does not pollute the global environment and can clearly show dependencies.

The AMD mode can be used in a browser environment, and allows asynchronous loading of modules, or dynamically loading modules as needed.

Configuring the Require.js:config Method

The Require method itself is also an object with a config method to configure the Require.js run parameters. The Config method accepts an object as a parameter.

require.config({    paths: {        jquery: [            ‘//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js‘,            ‘lib/jquery‘        ]    }});

The parameter object of the Config method has the following key members:

(1) Paths

The paths parameter specifies the location of each module. This location can be a relative location on the same server, or it can be an external URL. You can define multiple locations for each module, and if the first location fails to load, the second location is loaded, and the example above indicates that if the CDN fails to load, the standby script on the server is loaded. Note that when you specify a local file path, you can omit the file's last JS suffix name.

require(["jquery"], function($) {    // ...});

The above code loads the jquery module because the path to jquery is already defined in the paths parameter, so it will be downloaded in a predetermined location.

(2) BaseUrl

The BaseURL parameter specifies the base directory for the local module location, that is, the path of the local module is relative to which directory. This property is typically specified by the Data-main property when the Require.js is loaded.

(3) Shim

Some libraries are not AMD compatible, so you need to specify the value of the Shim property. Shim can be interpreted as "shims" to help require.js load non-AMD spec libraries.

require.config({    paths: {        "backbone": "vendor/backbone",        "underscore": "vendor/underscore"    },    shim: {        "backbone": {            deps: [ "underscore" ],            exports: "Backbone"        },        "underscore": {            exports: "_"        }    }});

The backbone and underscore in the code above are the non-AMD spec libraries. Shim specify their dependencies (Backbone depends on underscore), as well as the output symbol (Backbone is "Backbone" and Underscore is "_").

Plug - ins

Requirejs allows the use of plug-ins to load data in various formats. The full plugin list can be viewed on the official website.

The following is an example of the text plugin used to insert textual data.

define([    ‘backbone‘,    ‘text!templates.html‘], function( Backbone, template ){   // ...});

The first module loaded in the code above is backbone, the second module is a text, with ' text! ' Said. The text is used as a string and is stored in the template variable of the callback function.

Optimizer R.js

Requirejs provides a command-line tool r.js based on node. js to compress multiple JS files. Its primary role is to combine multiple module file compression into a single script file to reduce the number of HTTP requests for Web pages.

The first step is to install r.js (assuming node. JS is already installed).

npm install -g requirejs

Then, when used, type the command directly at the command line in the following format.

node r.js -o <arguments>

<argument> represents a series of parameters that are required when the command is run, such as the following:

node r.js -o baseUrl=. name=main out=main-built.js

In addition to providing parameter settings directly on the command line, you can also write parameters to a file, assuming the file name is build.js.

({    baseUrl: ".",    name: "main",    out: "main-built.js"})

Then, run the parameter file with R.js at the command line, OK, no additional steps are required.

node r.js -o build.js

The following is an example of a parameter file, assuming that the location is in the root directory and the file name is build.js.

({    appDir: ‘./‘,    baseUrl: ‘./js‘,    dir: ‘./dist‘,    modules: [        {            name: ‘main‘        }    ],    fileExclusionRegExp: /^(r|build)\.js$/,    optimizeCss: ‘standard‘,    removeCombined: true,    paths: {        jquery: ‘lib/jquery‘,        underscore: ‘lib/underscore‘,        backbone: ‘lib/backbone/backbone‘,        backboneLocalstorage: ‘lib/backbone/backbone.localStorage‘,        text: ‘lib/require/text‘    },    shim: {        underscore: {            exports: ‘_‘        },        backbone: {            deps: [                ‘underscore‘,                ‘jquery‘            ],            exports: ‘Backbone‘        },        backboneLocalstorage: {            deps: [‘backbone‘],            exports: ‘Store‘        }    }})

The above code merges multiple module compression into a single main.js.

The key members of the parameter file are interpreted as follows:

    • appdir: The project directory, relative to the location of the parameter file.

    • BASEURL: The location of the JS file.

    • dir: Output directory.

    • modules: An array containing objects, each of which is a module to be optimized.

    • fileexclusionregexp: Any file name that matches the regular expression will not be copied to the output directory.

    • optimizecss: Automatic compression of CSS files, the desirable values include "none", "standard", "Standard.keeplines", "standard.keepcomments", " Standard.keepComments.keepLines ".

    • removecombined: If True, the merged original file will not remain in the output directory.

    • paths: The relative path of each module, you can omit the JS suffix name.

    • Shim: Configures dependency relationships. If a module is not defined in AMD mode, you can use the Shim property to specify the module's dependency relationship and output value.

    • generatesourcemaps: Whether to generate a source map file.

A more detailed explanation can be found in the official documentation.

After you run the optimize command, you can go to the Dist directory to view the optimized files.

Here is another example of build.js.

({    mainConfigFile : "js/main.js",    baseUrl: "js",    removeCombined: true,    findNestedDependencies: true,    dir: "dist",    modules: [        {            name: "main",            exclude: [                "infrastructure"            ]        },        {            name: "infrastructure"        }    ]})

The above code merges the module file compression into two files, the first is main.js (specify exclude Infrastructure.js), and the second is infrastructure.js.

Requirejs and AMD Specifications

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.