JS modular Development (requireJS)

Source: Internet
Author: User

JS modular Development (requireJS)

Advantages of modular development:
Expose interface through exports. This means that no namespace is required, and no global variables are required. This is a thorough solution to naming conflicts.
Use require to introduce dependencies.This enables built-in dependencies. Developers only need to care about the dependencies of the current module. Other tasks such as Sea. js/Require. js will be automatically handled. For module developers, this is a good separation of attention, allowing programmers to enjoy more coding fun.

There are currently two specifications for implementing JS modular development: one is AMD specification and the other is CMD specification.
RequireJS follows AMD specifications. AMD advocates dependency on preconditions.
The CMD specification that SeaJS complies. CMD advocates nearby dependencies (loaded as needed)
AMD: APIs vary according to the scope of use, but use the same API
CMD: each API has a single responsibility

AMD standard module Style
1. Define the module with the module variable. It has a declare method.
2. declare accepts a parameter of the function type, for example, factory
3. factory has three parameters: require, exports, and module. factory uses the return value and exports to export API. factory. If it is an object type, this object is output as a module.

define(function(require, exports, module) {    var base = require('base');     exports.show = function() {    // todo with modulebase     } });

Use require to obtain the dependency module and use the exports export API.
In addition to require, AMD reserves a keyword require. As a globally reserved identifier, require can be implemented as modile loader.
AMD libraries include RequireJS, curl, Dojo, and Nodules.

RequireJS and seaJS have their own merits. However, since requireJS was used in one of my previous projects, I chose to conduct in-depth research on requireJS.
RequireJs
(1) asynchronous loading of js files to prevent webpage response loss;
(2) Management Module dependencies to facilitate code compilation and maintenance.

Introduction to RequireJS usage.
Requirejs official website is: http://requirejs.org/
Http://requirejs.org/docs/release/2.1.20/minified/require.js
Download require. js first.

Require. config is used to define aliases and configure aliases under the paths attribute. Then, use requirejs (parameter 1, parameter 2); parameter 1 is an array, and the name of the module to be referenced is input. The second parameter is a callback function, and the callback function is used to input a variable, replace the introduced module.
Loading require. js
1. load at the bottom of the page.
2,<script src="js/require.js" defer async="true" ></script>
On the async attribute surface, this file needs to be asynchronously loaded to avoid webpage response loss. IE does not support async and the defer attribute must be used.
After loading require. js, the next step is to load our own code.

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

The data-main attribute specifies the main module of the webpage program.
Main. js File

The introduction module can also write only require (). Requirejs defines the module through define (), and the parameters are the same. Methods and variables in this module cannot be accessed externally. Only return is returned.
In the require project, do not write. js extension names for all files to be introduced, because requirejs will automatically add. js extension names.
Define Module

Name this module math. js and save it.
The define module method can only be used in independent js files and cannot be used directly on pages.
Otherwise, the Mismatched anonymous define () module error is reported.
No dependency
If the defined module does not depend on other modules, you can:

AMD recommends a style by returning an object as the module object. The CommonJS style exposes the module object by assigning values to the module. exports or exports attributes.
When writing a module without any dependencies, and only returning an object contains some function Functions

Circular dependency
In some cases, we may need functions in modules moduleA and moduleA to depend on some applications. This is circular dependency.

Math. js module Introduction Method

The require () function defined by AMD specifications:

require(['moduleA', 'moduleB', 'moduleC'],     function (moduleA, moduleB, moduleC){    // some code here  });

The require () function accepts two parameters. The first parameter is an array that indicates the dependent modules. In the preceding example, ['lelea', 'leleb', 'lelec'] indicates that the main module depends on these three modules; the second parameter is a callback function. After all the modules specified in the current interface are loaded successfully, it will be called. The loaded module will pass in the function as a parameter, so that these modules can be used within the callback function.
Require () asynchronously loads moduleA, moduleB, and moduleC, And the browser does not lose the response. The callback function specified by require () runs only after the previous modules are loaded successfully, solved the problem of dependency.
Assuming that the main module depends on jquery, underscore, and backbone, main. js can write as follows:

require(['jquery', 'underscore', 'backbone'], function ($, _, Backbone){    // some code here  });

Require. js loads jQuery, underscore, and backbone first, and then runs the callback function. The code of the main module is written in the callback function.

Module Loading

The dependent modules of the main module are ['jquery ', 'underscore', 'backone']. By default, require. js assumes that the three modules are in the same directory as main. js. The file names are jquery. js, underscore. js, and backbone. js, and then load them automatically.
Using the require. config () method, we can customize the loading behavior of the module. Require. config () is written in the header of the main module (main. js. The parameter is an object. The paths attribute of this object specifies the loading path of each module.

The above Code provides the file names of the three modules. The path is in the same directory (js subdirectory) as main. js by default ). If these modules are in other directories, such as the js/lib directory, there are two writing methods. One is to specify paths one by one.

The other is to directly change the base Directory (baseUrl ).

If a module is on another host, you can directly specify its url, for example:

Require. js requires that each module is a separate js file. In this way, if multiple modules are loaded, multiple HTTP requests will be sent, which will affect the webpage loading speed. Therefore, require. js provides an optimization tool. After the module is deployed, you can use this tool to merge multiple modules into one file to reduce the number of HTTP requests.
In the code, require is a file multiple times, and does not cause the browser to load it repeatedly. Even if it is repeatedly require, it will load it only once.
CDN rollback: When CDN loading is incorrect, it is rolled back to the corresponding local database 2 through require. config.

AMD module writing

The modules loaded by require. js adopt AMD specifications. That is to say, the module must be written according to AMD regulations.
Specifically, the module must be defined using a specific define () function. If a module does not depend on other modules, it can be directly defined in the define () function.
// Math. js

The loading method is as follows:

If this module depends on other modules, the first parameter of the define () function must be an array that specifies the dependency of this module.

When the require () function loads the above module, it loads the myLib. js file first. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Examples + examples/examples + examples/K/bao0uW1xMSjv + examples/examples + examples/LbgtcS/4rKisru3 + examples/MPHtcS7sKOssdjQ68/Examples "here write image description" src = "http://www.bkjia.com/uploads/allimg/160414/04502520Y-14.png" title = "\"/>
Require. config () accepts a configuration object. In addition to the paths attribute mentioned earlier, this object also has a shim attribute, which is used to configure incompatible modules. Specifically, each module must define (1) the exports value (output variable name), indicating the name used for external calls of this module; (2) deps array, indicating the dependency of this module.

Obtain the module address.

var path = require.toUrl("./style.css");

JSONP

Require. js plugin

Require. js also provides a series of plug-ins to implement some specific functions.
The domready plug-in allows the callback function to run after the DOM structure of the page is loaded.

The text and image extensions allow require. js to load text and image files.

Similar plug-ins include json and mdown, which are used to load json files and markdown files.

R. js Compression

Require. js provides a script for r. js, which can compress all used modules into a script file. r. js can be executed using node. js.
Before compressing a module, you need to write a configuration file indicating the main module name, the compressed file name, and which modules do not need to be compressed.
Do not compress modules that are not defined using define, including libraries such as jquery and backbone and Their plug-ins.

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.