This is the first day of my participation in the August Challenge. For details, see:August is more challenging
Advantages of modularity: 1. Avoid global variable contamination; 2. Easy to write and maintain code
CommonJS (CJS)
Each file is a module with its own scope. Variables, functions, and classes in the file are private and invisible to other files. Inside a module, the module variable represents the current module. This variable is an object whose exports property (module.exports) is the external interface. If you load a module, you load the module.exports property of that module. Such as:
module.exports.x = x; module.exports.addX = addX; / / or module exports = {x, addX}Copy the code
If a variable or function wants to be a public variable that can be accessed in another file, it needs to be hung on global. (This is not recommended) For example:
global.warning = true;
Copy the code
CJS is a synchronous import module. You can import a library from modules or a file from a local directory. Use the require method to load the module
When CJS imports, it gives you a copy of the imported object.
const { sequelize } = require(".. /.. /core/db");Copy the code
CJS does not work in a browser and must be transformed and packaged. Node.js is a module specification that uses commonJs and can be used directly in a JS file.
The characteristics of
- All code runs in the module scope and does not contaminate the global scope.
- A module can be loaded multiple times, but it is only run once on the first load, and then the result is cached, and later loads read the cached result directly. For the module to run again, the cache must be cleared.
- Modules are loaded in the order in which they appear in the code.
Reference: javascript.ruanyifeng.com/nodejs/modu…
ESM ES module
This is Javascript’s proposal to implement a standard module system that is available in many modern browsers. You can call it in HTML, but you need to add the attribute type= ‘module’ to the script tag.
<script type="module">
import {func1} from 'my-lib';
func1();
</script>
Copy the code
You can import local files, libraries, or remote modules. (static)
Import {createStore} from "https://unpkg.com/[email protected]/es/redux.mjs"; import * as myModule from './util.js';Copy the code
In addition to being able to import statically, you can also import dynamically. ES modules are really JavaScript objects: we can deconstruct their properties and call any of their public methods. Such as:
btn.addEventListener("click", () => { // loads named export import("./util.js").then(({ funcA }) => { funcA(); }); }); Or const loadUtil = () => import("./util.js"); // Return a promise. Btn.addeventlistener ("click", () => {loadUtil().then(module => {module.funca (); module.default(); })}) btn.addeventListener ("click", async () => {const utilsModule = await loadUtil(); utilsModule.funcA(); utilsModule.default(); })Copy the code
With dynamic imports, you can split your code and load only the important code at the right time. Before JavaScript introduced dynamic imports, this pattern was unique to WebPack (the module binder). Examples like React and Vue load blocks of code that respond to events, such as user interactions or routing changes, by dynamically importing code splits.
When you import a JSON file, the data in the JSON file is directly exported
advantages
With CJS’s simple syntax and AMD’s asynchronism, the ESM allows packers like Rollup to get faster loading by removing unnecessary code and reducing the number of code packages.
Reference: blog.csdn.net/hpc_kiven/a…
AMD asynchronous module definition
AMD is built for the front end (while CJS is the back end), and AMD syntax is not as intuitive as CJS syntax. Example:
define(['dep1', 'dep2'], function (dep1, dep2) {
//Define the module value by returning a value.
return function () {};
});
// "simplified CommonJS wrapping" https://requirejs.org/docs/whyamd.html
define(function (require) {
var dep1 = require('dep1'),
dep2 = require('dep2');
return function () {};
});
Copy the code
UMD Universal Module Definition
Available on both front and back ends, unlike CJS or AMD, UMD is more of a mode for configuring multiple module systems and is often used as a standby module when using packers such as Rollup/Webpack
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(["jquery", "underscore"], factory);
} else if (typeof exports === "object") {
module.exports = factory(require("jquery"), require("underscore"));
} else {
root.Requester = factory(root.$, root._);
}
}(this, function ($, _) {
// this is where I defined my module implementation
var Requester = { // ... };
return Requester;
}));
Copy the code