This is the 30th day of my participation in the August Challenge
preface
What is modularity?
Breaking a large program into smaller interdependent files based on function or business and reassembling them in a simple way;
A module is a file. A script is a module
Why modularity?
Without modularization, all script tags must be in the correct order, otherwise they will rely on errors, global variables have naming conflicts, memory usage cannot be reclaimed, and IIFE/namespace will lead to many problems such as low code readability.
CommonJS specification
Export the module writing method
/ / 1 ✔ ️ module. Exports = {a: 'Hi' b: 'Axjy} / / 2 ✔ ️ module. Exports. A =' Axjy '; // mode 3✔️ exports. A = 'Axjy'; ❌ exports = {a: 'Hi', b: 'Axjy'}Copy the code
Why is the last one wrong?
Because Node provides an exports variable for each module, pointing to module.exports. This equates to a line of command in the header of each module.
As a result, methods can be added to exports objects when exporting module interfaces.
Exports cannot be directly pointed to a value, because that would break the link between exports and module.exports, causing exports to no longer point to module.exports
Loading mode:
- Loading a built-in module
require('fs')
[Node.js built-in module] - Load the file module of the (relative/absolute) path
require('/User/.. /file.js')
require('./file.js')
- Load the NPM package
require('lodash')
【 bynpm i lodash
Download thenode_modules
Module 】
To find the principles
Built-in modules: directly skip path analysis and file location
Path module: get the relative path directly
NPM package lookup rules:
-
Current directory node_modules
-
If not, node_modules of the parent directory
-
If not, recurse up the path to node_ modules in the root directory
-
If package.json is not found, the file will be loaded. If package.json is not found, the file will be searched for index.js, index.json, and index.node in sequence
Note:
-
Require () is a global method in Node, so it cannot be used directly in HTML;
-
Require is not unique to CommonJS, which is just one of many specifications
-
The arguments to require() can be variables or string concatenations
CommonJS specification features
-
All code runs in the module scope and does not pollute the global scope.
-
Modules can be loaded multiple times, but only run once on the first load, and then the results are cached and read directly from the cache when they are loaded later. For the module to run again, the cache must be cleared.
-
The order in which modules are loaded, in the order they appear in the code.
Require. The cache contains loaded modules. The reason for the cache is synchronous loading
- File module search time, if every require needs to search again, the performance will be poor;
- In real development, modules may contain side effect code
More module loading specifications
ES Modules (ESM)
ES Modules (ESM), a language-level modularity specification that is context-independent and compiled with Babel
- ESM is a modular standard proposed in ES6 language level.
- The ESM contains import and export keywords, but cannot console two keywords
Out before the statement
The following exports are valid
Array / / export export let up = [' Jan, Feb, Mar, Apr, Aug, Sep, Oct, Nov, Dec ']. // export const MODULES_BECAME_STANDARD_YEAR = 2015; // Export class User {constructor(name) {this.name = name; Export function sayHi(user) {alert(' Hello, ${user}! `); }Copy the code
Export and declaration are separated
export {sayHi, sayBye}; // Export the list of variablesCopy the code
The Export “as”
You can use AS to give the export a different name.
export {sayHi as hi, sayBye as bye};
Copy the code
The import import
Writing:
import {sayHi, sayBye} from './say.js';
import * as say from './say.js';
Copy the code
Example:
We can list the things we want to import in curly braces import {… }
If you have a lot of content to import, you can use import * as
to import everything as a single object
You are advised to use method 1, which explicitly lists the content to be imported
The Import “as”
You can use AS to give imports different names.
Export default
The module provides a special export default syntax to make “a module does only one thing”
Place export default in front of the entity to export:
This type of export does not require curly braces for import
Note:
-
You can have both a default export and a named export in a module, but in practice you don’t usually mix them.
-
A module is either a named export or a default export.
-
Since there can be at most one default export per file, the exported entity may not have a name.
-
An export named import requires curly braces,
-
Import The default export does not require curly braces.
If there is no default, the following will be an error
CommonJS VS ESM
* can mix, but it is not recommended (import commonjs | | the import of the require)
The difference between
Other module specifications
AMD is RequireJS in the promotion process of standardized output, asynchronous loading, advocate dependency preloading;
CMD is the standardized output of SeaJS in the promotion process, asynchronous loading, advocating the nearest dependence;
UMD (Universal Module Definition) specification, compatible with AMD and CommonJS mode
conclusion
Reference:
JavaScript standard Reference tutorial
The Modern JavaScript Tutorial
If any of the above is wrong, please point out in the comments section!
If there is a harvest, leave a thumbs-up to encourage it! 🍜