What it does: Improve code reuse Typically a file is a module, with its own scope, exposing only specific variables and functions.

CommonJS

Node.js is a major practitioner of the commonJS specification and has four important environment variables to support modular implementations: Module, exports, require, global

CommonJS loads modules synchronously and does not perform subsequent operations until the module is loaded. On the server side, the module files are stored on local disk and are very fast to read, so this should not be a problem. However, on the browser side, it is more reasonable to use asynchronous loading for network reasons.

AMD and require. Js

The AMD specification uses asynchronous loading of modules, which does not affect the execution of subsequent statements. All statements that depend on this module are defined in a callback function that will not run until the load is complete.

Here is an introduction to implement the modularization of the AMD specification with require.js: specify the reference path with require.config(), define the module with define(), and load the module with require().

<script SRC ="js/require.js" data-main="js/main"></script> /** main.js entry file /main module **/ / Config ({baseUrl: "js/lib", paths: {"jquery": // server /lib/jquery.min. Js "underscore": "underscore. Min ",}}); // Server /lib/jquery.min. // require(["jquery","underscore"],function($,_){// some code here}); require(["jquery","underscore"],function($,_){// some code here}); Math.js module define(function () {var basicNum = 0; var add = function (x, y) { return x + y; }; return { add: add, basicNum :basicNum }; }); // Define (['underscore'],function(_){var classify = function(list){ _.countBy(list,function(num){ return num > 30 ? 'old' : 'young'; })}; return { classify :classify }; // require(['jquery', 'math'],function($, math){var sum = math.add(10,20); $("#sum").html(sum); });Copy the code

CMD and sea. Js

Require.js loads and executes the code in the module when it declares a dependent module

define(["a", "b", "c", "d", "e", "f"], function(a, b, c, d, e, If (false) {if (false) {if (false) {if (false) {if (false) {if (false) {if (false) {if (false) {if (false) {if (false) {if (false)}});Copy the code

CMD is another JS modularity solution that is similar to AMD except that:

AMD advocates relying on front-loading and front-loading execution, while CMD advocates relying on nearby and delayed execution. This specification was actually created during the promotion of Sea-js.

AMD writing / * * * * / define ([" a ", "b", "c", "d", "e", "f"], function (a, b, c, d, e, F) {// all modules that need to be used are declared and initialized first. If (false) {// do something ()}}); Define (function(require, exports, module) {var a = require('./a'); // declare a.dosomething () if needed; if (false) { var b = require('./b'); b.doSomething(); }}); Math.js define(function(require, exports, module) {var $= require('jquery.js'); var add = function(a,b){ return a+b; } exports.add = add; }); Seajs. use(['math.js'], function(math){var sum = math.add(1+2); });Copy the code

The difference between AMD and CMD

CMD is another JS modularity solution that is similar to AMD except that:

AMD advocates relying on front-loading and front-loading execution, while CMD advocates relying on nearby and delayed execution.

ES6 Module

ES6, on the level of language standards, implements module functions, and implements them quite simply, aiming to become a common module solution for browsers and servers. Its module functions are mainly composed of two commands: export and import. The export command is used to specify the external interface of a module, and the import command is used to input functions provided by other modules

Copy the code

ES6 modules are not objects, and the import command is statically analyzed by the JavaScript engine. The module code is introduced at compile time, rather than loaded at run time, so conditional loading cannot be implemented. Because of this, static analysis is possible.

Differences between ES6 modules and CommonJS modules

  1. The CommonJS module prints a copy of the value, the ES6 module prints a reference to the value.

The CommonJS module outputs a copy of the value, meaning that once a value is output, changes within the module do not affect that value. ES6 modules operate differently from CommonJS. When the JS engine statically analyzes a script, it generates a read-only reference to the module load command import. When the script is actually executed, it will be evaluated in the loaded module based on the read-only reference. In other words, the IMPORT of ES6 is a bit like the “symbolic link” of Unix systems, where the original value changes and the import load value changes with it. Therefore, ES6 modules are referenced dynamically and do not cache values. Variables in modules are bound to the module in which they are located.

  1. The CommonJS module is run time loaded, and the ES6 module is compile time output interface.

Runtime loading: CommonJS modules are objects; That is, the entire module is loaded on input, an object is generated, and methods are read from that object. This loading is called “runtime loading.”

Compile-time loading: ES6 modules are not objects, but are output code explicitly specified through the export command and static commands when importing. That is, when you import, you can specify that an output value is loaded instead of the entire module, which is called “compile-time loading.”

CommonJS loads an object (that is, the module.exports property) that is generated only after the script runs. An ES6 module is not an object, and its external interface is a static definition that is generated during the code static parsing phase.

  • CommonJS is only generated when the script runs, ES6 modules are generated at compile time;

  • CommonJS loads an object. An ES6 module is not an object. Its external interface is a static definition.

  • CommonJS is loaded at runtime, ES6 modules are loaded at compile time;

  • The CommonJS module prints a copy of a value (once a value is printed, changes within the module do not affect the value), whereas the ES6 module prints a reference to the value.

  • CommonJS loads modules synchronously

  • ES6 language standard

  • The ES6 Module syntax is the standard way to write JavaScript modules; stick with it. Use import instead of require.

  • Replace module.exports with export.

Var React = require(' React '); var Breadcrumbs = React.createClass({ render() { return <nav />; }}); module.exports = Breadcrumbs; // ES6: import React from 'React '; class Breadcrumbs extends React.Component { render() { return <nav />; }}; export default Breadcrumbs;Copy the code
  1. If the module has only one output value, export Default is used
  2. If the module has multiple output values, do not use export Default
  3. Do not use export default and ordinary export together.
  4. Do not use wildcards in module input. This ensures that you have an export default in your module.
// bad
import * as myObject from './importModule';

// good
import myObject from './importModule';
Copy the code
  • If the module defaultsThe outputaFunction, the first letter of the function name should be lowercase.
  • If the module defaultsThe outputaObject, the first letter of the object name should be capitalized.

Juejin. Cn/post / 684490…