Modularization is very important in the project. a complicated project must have many similar functional modules. If you need to re-compile the module every time, it will be time-consuming and labor-intensive. However, the premise for referencing modules written by others is to have a uniform "open posture". If each person has their own writing method, it will certainly be messy. Below we will introduce several modular specifications of JS. Modularization is very important in the project. a complicated project must have many similar functional modules. If you need to re-compile the module every time, it will be time-consuming and labor-intensive. However, the premise for referencing modules written by others is to have a uniform "open posture". If each person has their own writing method, it will certainly be messy. Below we will introduce several modular specifications of JS.
Modularization is very important in the project. a complicated project must have many similar functional modules. If you need to re-compile the module every time, it will be time-consuming and labor-intensive. However, the premise for referencing modules written by others is to have a uniform "open posture". If each person has their own writing method, it will certainly be messy. Below we will introduce several modular specifications of JS.
I. modular process 1: script tag
This is the most primitive JavaScript file loading method. If every file is regarded as a module, their interfaces are usually exposed in the global scope, that is, defined in the window object, interface calls of different modules are in the same scope. Some Complex frameworks use namespaces to organize interfaces of these modules.
Disadvantages:
1. Global scope of contamination
2. Developers must solve the dependency between modules and code libraries.
3. files can only be loaded in the writing order of script labels.
4. Various resources are difficult to manage in large projects, and problems accumulated over the long term make the code library messy.
Ii. modularization process II: CommonJS specifications
The core idea of this specification is to allow the module to synchronously load other modules to be dependent through the require method, and then export the interface to be exposed through exports or module. exports.
require("module");require("../file.js");exports.doStuff = function(){};module.exports = someValue;
Advantages:
1. Simple and Easy to use
2. Easy reuse of server-side modules
Disadvantages:
1. synchronous module loading is not suitable for the browser environment. Synchronization means blocking loading and asynchronous loading of browser resources.
2. Non-blocking concurrent loading of multiple modules
Differences between module. exports and exports
1. exports is a reference to module. exports.
2. The initial value of module. exports is an empty object {}, so the initial value of exports is {}
3. require () returns module. exports instead of exports.
Exports example:
// app.jsvar circle = require('./circle');console.log(circle.area(4));// circle.jsexports.area = function(r){ return r * r * Math.PI;}
Module. exports example:
// app.jsvar area = require('./area');console.log(area(4));// area.jsmodule.exports = function(r){ return r * r * Math.PI;}
Error:
// app.jsvar area = require('./area');console.log(area(4));// area.jsexports = function(r){ return r * r * Math.PI;}
In fact, it overwrites exports, that is, exports points to a new memory (the content is a function for calculating the circular area), that is, exports and module. exports no longer point to the same memory, that is, exports and module. exports is unrelated, that is, module. the memory that exports points to is still an empty object {}, that is, area. js exports an empty object, so we are in the app. when area (4) is called in js, a TypeError: object is not a function error is reported.
Summary:When we want the module to export an object, exports and module. exports can be used (but exports cannot be overwritten as a new object). to export a non-object interface, you must also override the module. exports.
3. modular process 3: AMD specifications
Because the modules on the browser end cannot be loaded synchronously, the subsequent Module loading and execution will be affected. Therefore, the AMD (Asynchronous Module Definition) specification is born.
The AMD standard defines the following two APIs:
1. require ([module], callback );
2. define (id, [depends], callback );
The require interface is used to load a series of modules, and the define interface is used to define and expose a module.
Example:
define("module", ["dep1", "dep2"], function(d1, d2){ return someExportedValue;});require(["module", "../file"], function(module, file){ /* ... */ });
Advantages:
1. It is suitable for Loading modules asynchronously in the browser environment.
2. Multiple modules can be loaded in parallel.
Disadvantages:
1. It increases the development cost, makes it difficult to read and write code, and the semantics of the module definition method is not smooth.
2. It does not conform to the general modular way of thinking and is a compromise.
4. modular process 4: CMD specifications
The CMD (Common Module Definition) specification is similar to AMD and should be kept as simple as possible. It also maintains great compatibility with the CommonJS and Node. js Modules specifications. In the CMD specification, a module is a file.
Example:
define(function(require, exports, module){ var $ = require('jquery'); var Spinning = require('./spinning'); exports.doSomething = ... module.exports = ...})
Advantages:
1. Dependency nearby, delayed execution
2. It is easy to run in Node. js
Disadvantages:
1. dependent on SPM packaging. The module loading logic is biased
What is the difference between AMD and CMD?
AMD and CMD are very similar, but there are still some minor differences. Let's take a look at their differences:
1. AMD executes the dependent modules in advance, while CMD delays the execution.
2. AMD advocates dependency front-end; CMD advocates dependency proximity, and require only when a module is used. Check the Code:
// AMDdefine (['. /','. /B '], function (a, B) {// dependencies must be written to a at the beginning. doSomething () // 100 rows B are omitted here. doSomething ()...}); // define (function (require, exports, module) {var a = require ('. /A'). doSomething () // skip the 100 rows var B = require ('. /B ') // dependency can be written nearby. doSomething ()//...});
3. By default, AMD APIs are used for multiple purposes. CMD APIs are strictly differentiated and single responsibilities are highly respected.
5. modular process 5: ES6 Modular
The EcmaScript6 standard adds the module system definition at the JavaScript language level. The design philosophy of the ES6 module is to be as static as possible, so that the module dependency and input and output variables can be determined during compilation. The CommonJS and AMD modules can only determine these items at runtime.
In ES6, we use the export keyword to export the module and the import keyword to reference the module. It should be noted that the ES6 standard is not directly related to the current standard, and few JS engines currently support it directly. Therefore, Babel's practice is to translate unsupported imports into currently supported require.
Although the current use of import is not much different from require (essentially one thing), it is strongly recommended to use the import keyword, because once the JS engine can parse the import keyword of ES6, the entire implementation method will be significantly different from the current one. If the import keyword is used at present, the code changes will be very small in the future.
Example:
import "jquery";export functiondoStuff(){}module "localModule" {}
Advantages:
1. Easy Static Analysis
2. Future-oriented EcmaScript standards
Disadvantages:
1. The native browser has not implemented this standard
2. New command words supported by the new version of Node. js
The above is a detailed explanation of javascript modularization. For more information, see other related articles in the first PHP community!