What is modular development? In front-end development, at first, as long as dozens of hundreds of lines of code are embedded in the script tag, some basic interaction effects can be achieved. Later, JavaScript was valued and widely used. jQuery, Ajax, node. js, MVC...
What is modular development?
In front-end development, at first, as long as dozens of hundreds of lines of code are embedded in the script tag, some basic interaction effects can be achieved. Later, JavaScript was valued and widely used. jQuery, Ajax, node. the help of Js, MVC, and MVVM makes front-end development more and more important, and also makes front-end projects more and more complex. However, JavaScript does not provide any obvious help for organizing code, there is no concept of a class, let alone a module. What is a module?
A module is a file that implements specific functions. With a module, we can more easily use others' code and load modules as needed. The module development must follow certain specifications, otherwise it will be messy.
According to AMD specifications, we can use the define definition module and the require call module.
Currently, common js module specifications include CommonJS and AMD.
AMD specifications
AMD is Asynchronous Module Definition. The Chinese name is "Asynchronous Module Definition. It is a specification for browser-side modular development, and the server-side specification is CommonJS
The module is asynchronously loaded without affecting the running of subsequent statements. All statements that depend on certain modules are placed in the callback function.
AMD is the standardized output of modules defined by RequireJS in the promotion process.
Define () function
The AMD Specification defines only one function define, which is a global variable. The function is described as follows:
define(id?, dependencies?, factory);
Parameter description:
Id: the name of the module in the definition. Optional. If this parameter is not provided, the module name should be the name of the specified script requested by the module loader by default. If this parameter is provided, the module name must be "top-level" and absolute (relative names are not allowed ). Dependencies: the array literal of the module ID that the current module depends on. The dependency parameter is optional. If this parameter is ignored, it should be ["require", "exports", "module"] by default. However, if the Length attribute of the factory method is less than 3, the loader selects the number of parameters specified by the function Length attribute to call the factory method. Factory method. The module initializes the function or object to be executed. If it is a function, it should be executed only once. If it is an object, this object should be the output value of the module.
Module name format
The module names are used to uniquely identify the modules in the definition. They are also used in the dependency array:
The module name is a string of meaningful words separated by a forward slash ". ",".. "the module name cannot be in the format of a file extension, such as". js "module name can be" relative "or" top-level ". If the first character is ". "or"... it is the relative Module name. The top-level module name is parsed from the concept module of the root namespace.
Use require and exports
Create a module named "alpha" using require, exports, and a module named "beta:
define("alpha", ["require", "exports", "beta"], function (require, exports, beta) { exports.verb = function() { return beta.verb(); //Or: return require("beta").verb(); } });
Require API Introduction :#
AMD standard Chinese version: # (% E4 % B8 % AD % E6 % 96% 87% E7 % 89% 88)
Currently, AMD libraries include RequireJS, curl, Dojo, and Nodules.
CommonJS specifications
CommonJS is the specification of the server-side module. Node. js adopts this specification. Node. JS first adopts the modular concept of js.
According to CommonJS specifications, a single file is a module. Each module is a separate scope. That is to say, variables defined within the module cannot be read by other modules unless defined as the attribute of the global object.
The best way to output module variables is to use the module. exports object.
var i = 1;var max = 30;module.exports = function () { for (i -= 1; i++ < max; ) { console.log(i); } max *= 1.1;};
The code above defines a function through the module. exports object, which is a bridge between the external and internal communication of the module.
The loading module uses the require method to read and execute a file, and finally return the module. exports object in the file.
CommonJS specifications :#
RequireJS and SeaJS
RequireJS was created by James Burke and is also the founder of AMD standards.
The define method is used to define a module. RequireJS requires that each module be placed in a separate file.
Both RequireJS and Sea. js are module loaders and advocate the idea of modular development. The core value is to make the modular development of JavaScript simple and natural.
The biggest difference between SeaJS and RequireJS:
SeaJS's attitude towards modules is lazy execution, while RequireJS's attitude towards modules is pre-execution.
Do not understand? Read this illustrated article :#
RequireJS API :#
RequireJS usage :#
Why use requireJS?
Imagine if a webpage contains many js files, the browser will first load the js file when downloading the page to stop rendering the webpage. If there are more files, the browser may lose response. Second, to ensure the dependency of js files, the module (File) with the largest dependency should be placed at the end of the load. When the dependency is very complex, coding and maintenance will become difficult.
RequireJS was born to solve these two problems:
(1) asynchronous loading of js files to avoid webpage response loss; (2) dependency between management modules, facilitating code compilation and maintenance.
Download RequireJS files :#
AMD and CMD
CMD (Common Module Definition) general Module Definition. This specification defines the basic writing format and basic interaction rules of the module. This specification is developed in China. AMD is a front-end of dependency, and CMD is loaded on demand.
In the CMD specification, a module is a file. The code is written in the following format:
define(factory);
When factory is a function, it indicates the construction method of the module. Run this constructor to obtain the interface provided by the module. When the factory method is executed, three parameters are input by default: require, exports, and module:
Define (function (require, exports, module) {// module code });
Require is a parameter that can be imported into other modules, while export can export some attributes and methods in the module.
CMD standard address :#
AMD is the standardized output of modules defined by RequireJS during promotion. CMD is the standardized output of modules defined by SeaJS during promotion.
For dependent modules, AMD runs ahead of schedule, while CMD executes ahead of schedule.
AMD: Execution ahead of schedule (asynchronous loading: dependency execution first) + delayed execution CMD: delayed execution (running to loading on demand, executed in order)
CMD advocates neighborhood, while AMD recommends that the neighborhood be dependent on the neighborhood. See the following code:
// Define (function (require, exports, module) {var a = require ('. /A'). doSomething () // skip the 100 rows var B = require ('. /B ') // dependency can be written nearby. doSomething ()//...}) // AMD recommends define (['. /','. /B '], function (a, B) {// dependencies must be written to a at the beginning. doSomething () // 100 rows B are omitted here. doSomething ()...})
Another difference is:
AMD: APIs vary according to the scope of use, but using the same api cmd: each api has a single responsibility
AMD has the following advantages: Asynchronous Parallel loading. Under AMD specifications, asynchronous loading will not produce errors.
The CMD mechanism is different. This loading method will produce errors. If you can standardize the module content format, you can also
Jquery1.7 and later versions are automatically modularized and support AMD mode: mainly using the define function. Although sea. js is a CommonJS specification, define is used to define modules.
So jQuery is automatically modularized.
Seajs. config ({'base': '/', 'Alias': {'jquery ': 'jquery. js' // defines the jquery file }});
The define function is similar to the define function of AMD:
Define (function (require, exports, module {// The module var $ = require ('jquery ') to be loaded first '); // then pass the jQuery object to the plug-in module require ('. /cookie ') ($); // start to use $. cookie method });How to use sea. js?