In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces what JavaScript modularization programs and tools have, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Modularity is an essential element of large front-end projects. Since the birth of JavaScript, there have been a variety of modular solutions, let's take an inventory together.
IIFE module
By default, variables defined in the browser hosting environment are global variables, and if the page references multiple such JavaScript files, it is easy to cause naming conflicts.
/ / define the global variable let count = 0; const increase = () = > + + count; const reset = () = > {count = 0; console.log ("Count is reset.");}; / / use the global variable increase (); reset ()
To avoid global contamination, you can wrap it in anonymous functions, which is the simplest IIFE module (function expression that executes immediately):
/ / define IIFE module const iifeCounterModule = (() = > {let count = 0; return {increase: () = > + + count, reset: () = > {count = 0; console.log ("Count is reset.");}};}) (); / / use IIFE module iifeCounterModule.increase (); iifeCounterModule.reset ()
IIFE exposes only one global module name with local variables inside, greatly reducing global naming conflicts.
Each IIFE module is a global variable, and these modules usually have their own dependencies. You can use dependent global variables directly within the module, or you can pass dependencies as parameters to IIFE:
/ / define IIFE modules with dependencies const iifeCounterModule = ((dependencyModule1, dependencyModule2) = > {let count = 0; return {increase: () = > + + count, reset: () = > {count = 0; console.log ("Count is reset.");}};}) (dependencyModule1, dependencyModule2)
Some popular libraries have adopted this pattern in earlier versions, such as the famous jQuery (the latest version is also starting to use the UMD module, which will be described later).
There is another kind of IIFE, which follows a format on the API declaration, that is, the variables corresponding to these API are defined in advance within the module, so that the API can call each other:
/ / Define revealing module. Const revealingCounterModule = () = > {let count = 0; const increase = () = > + + count; const reset = () = > {count = 0; console.log ("Count is reset.");}; return {increase, reset};}) (); / / Use revealing module. RevealingCounterModule.increase (); revealingCounterModule.reset ()
CommonJS module (Node.js module)
CommonJS, originally called ServerJS, is a modular scheme implemented by Node.js. By default, each .js file is a module, and a module and exports variable is provided inside the module to expose the module's API. Use require to load and use modules. The following code defines a counter module:
/ / define CommonJS module: commonJSCounterModule.js. Const dependencyModule1 = require (". / dependencyModule1"); const dependencyModule2 = require (". / dependencyModule2"); let count = 0; const increase = () = > + + count; const reset = () = > {count = 0; console.log ("Count is reset.");}; exports.increase = increase; exports.reset = reset; / / or this: module.exports = {increase, reset}
Use this module:
/ / use the CommonJS module const {increase, reset} = require (". / commonJSCounterModule"); increase (); reset (); / / or this: const commonJSCounterModule = require (". / commonJSCounterModule"); commonJSCounterModule.increase (); commonJSCounterModule.reset ()
At run time, Node.js wraps the code in the file in a function, and then passes the exports, module variables, and require functions in arguments.
/ / Define CommonJS module: wrapped commonJSCounterModule.js. (function (exports, require, module, _ _ filename, _ _ dirname) {const dependencyModule1 = require (". / dependencyModule1"); const dependencyModule2 = require (". / dependencyModule2"); let count = 0; const increase = () = > + count; const reset = () = > {count = 0; console.log ("Count is reset.");}; module.exports = {increase, reset} Return module.exports;}) .call (thisValue, exports, require, module, filename, dirname); / / Use CommonJS module. (function (exports, require, module, _ _ filename, _ _ dirname) {const commonJSCounterModule = require (". / commonJSCounterModule"); commonJSCounterModule.increase (); commonJSCounterModule.reset ();}) .call (thisValue, exports, require, module, filename, dirname)
AMD module (RequireJS module)
AMD (Asynchronous Module definition) is also a module format implemented by the library RequireJS. It defines the module through the define function and accepts the module name and dependent module name as parameters.
/ / define AMD module define ("amdCounterModule", ["dependencyModule1", "dependencyModule2"], (dependencyModule1, dependencyModule2) = > {let count = 0; const increase = () = > + count; const reset = () = > {count = 0; console.log ("Count is reset.");}; return {increase, reset};})
Also use require to load and use modules:
Require (["amdCounterModule"], amdCounterModule = > {amdCounterModule.increase (); amdCounterModule.reset ();})
Unlike CommonJS, the requrie here accepts a callback function, and the argument is the loaded module object.
The define function of AMD can also dynamically load the module, as long as you pass it a callback function with the require parameter:
/ / Use dynamic AMD module. Define (require = > {const dynamicDependencyModule1 = require ("dependencyModule1"); const dynamicDependencyModule2 = require ("dependencyModule2"); let count = 0; const increase = () = > + count; const reset = () = > {count = 0; console.log ("Count is reset.");}; return {increase, reset};})
The AMD module can also pass module and exports to define, so that CommonJS code can be used internally:
/ / define AMD module define ((require, exports, module) = > {/ / CommonJS code const dependencyModule1 = require ("dependencyModule1") with CommonJS code; const dependencyModule2 = require ("dependencyModule2"); let count = 0; const increase = () = > + + count; const reset = () = > {count = 0; console.log ("Count is reset.");}; exports.increase = increase; exports.reset = reset }); / / use AMD module define with CommonJS code (require = > {/ / CommonJS code const counterModule = require ("amdCounterModule"); counterModule.increase (); counterModule.reset ();})
UMD module
UMD (Common Module definition) is a modular format that supports multiple environments and can be used in both AMD and browser (or Node.js) environments.
Compatible with AMD and global introduction of browsers:
((root, factory) = > {/ / detect whether the define function if of AMD/RequireJS exists (typeof define = = "function" & & define.amd) {/ / if so, call factory define ("umdCounterModule", ["deependencyModule1", "dependencyModule2"], factory) within the define function } else {/ / otherwise it is a browser environment, and the dependency directly calling factory / / import is a global variable (property of window object) / / the exported module is also a global variable (property of window object) root.umdCounterModule = factory (root.deependencyModule1, root.dependencyModule2);}}) (typeof self! = = "undefined"? Self: this, (deependencyModule1, dependencyModule2) = > {/ / specific module code let count = 0; const increase = () = > + + count; const reset = () = > {count = 0; console.log ("Count is reset.");}; return {increase, reset};})
It looks complicated, but it's actually an IIFE. The code comments are very clear, you can take a look.
Here's a look at the UMD that is compatible with AMD and CommonJS (Node.js) modules:
(define = > define ((require, exports, module) = > {/ / Module Code const dependencyModule1 = require ("dependencyModule1"); const dependencyModule2 = require ("dependencyModule2"); let count = 0; const increase = () = > + + count; const reset = () = > {count = 0; console.log ("Count is reset.");}; module.export = {increase, reset} }) (/ / determine whether the module variable and exports variable in CommonJS exist / / at the same time determine whether the define function of AMD/RequireJS exists typeof module = = "object" & & module.exports & & typeof define! = = "function"? / / if it is CommonJS/Node.js Manually define a define function factory = > module.exports = factory (require, exports, module): / / if it is AMD/RequireJS, use the define function define directly)
Is also an IIFE, by judging the environment, choose to execute the corresponding code.
ES module (ES6 Module)
The above mentioned several module formats are implemented with a variety of techniques and look dazzling. Finally, in 2015, ECMAScript version 6 (ES 2015, or ES6) was born! It introduces a completely new module format, and the main syntax is the import and epxort keywords. Let's see how ES6 defines modules:
/ / define ES module: esCounterModule.js or esCounterModule.mjs. Import dependencyModule1 from ". / dependencyModule1.mjs"; import dependencyModule2 from ". / dependencyModule2.mjs"; let count = 0; / / named export: export const increase = () = > + + count; export const reset = () = > {count = 0; console.log ("Count is reset.");}; / / default export export default {increase, reset}
This module is used in the browser and type= "module" is added to the script tag to indicate that the ES module is introduced. When used in a Node.js environment, change the extension to .mjs.
/ / Use ES module. / / browser: or inline. / / Server: esCounterModule.mjs import {increase, reset} from ". / esCounterModule.mjs"; increase (); reset (); / / Or import from default export: import esCounterModule from ". / esCounterModule.mjs"; esCounterModule.increase (); esCounterModule.reset ()
If the browser does not support it, you can add a background attribute:
Alert ("Not supported.")
ES dynamic Module (ECMAScript 2020)
The built-in import function is introduced in the latest ESCMA standard version 11 in 2020, which is used to dynamically load ES modules. The import function returns a Promise and uses the loaded module in its then callback:
/ / load dynamic ES module import (". / esCounterModule.js"). Then (({increase, reset}) = > {increase (); reset ();}); import (". / esCounterModule.js"). Then (dynamicESCounterModule = > {dynamicESCounterModule.increase (); dynamicESCounterModule.reset ();})
Since Promise is returned, it must also support await usage:
/ / use ES dynamic module via async/await (async () = > {/ / named exported module const {increase, reset} = await import (". / esCounterModule.js"); increase (); reset (); / / default exported module const dynamicESCounterModule = await import (". / esCounterModule.js"); dynamicESCounterModule.increase (); dynamicESCounterModule.reset ();}) ()
The compatibility of each platform with import, export and dynamic import is as follows:
Image.png
Image.png
System module
SystemJS is an ES module syntax conversion library to support earlier versions of ES. For example, the following module is defined using the ES6 syntax:
/ / define ES module import dependencyModule1 from ". / dependencyModule1.js"; import dependencyModule2 from ". / dependencyModule2.js"; dependencyModule1.api1 (); dependencyModule2.api2 (); let count = 0; / / Named export: export const increase = function () {return + + count}; export const reset = function () {count = 0; console.log ("Count is reset.");}; / / Or default export: export default {increase, reset}
If the current running environment, such as an old browser, does not support ES6 syntax, the above code will not run. One solution is to convert the above module definition into an API, System.register of the SystemJS library:
/ / Define SystemJS module. System.register ([. / dependencyModule1.js ",". / dependencyModule2.js "], function (exports_1, context_1) {" use strict "; var dependencyModule1_js_1, dependencyModule2_js_1, count, increase, reset; var _ _ moduleName = context_1 & & context_1.id Return {setters: [function (dependencyModule1_js_1_1) {dependencyModule1_js_1 = dependencyModule1_js_1_1;}, function (dependencyModule2_js_1_1) {dependencyModule2_js_1 = dependencyModule2_js_1_1 ], execute: function () {dependencyModule1_js_1.default.api1 (); dependencyModule2_js_1.default.api2 (); count = 0; / / Named export: exports_1 ("increase", increase = function () {return + + count}) Exports_1 ("reset", reset = function () {count = 0; console.log ("Count is reset.");};); / Or default export: exports_1 ("default", {increase, reset});}} })
In this way, the import/export keyword is gone. Webpack, TypeScript, and so on can do this transformation automatically (I'll talk about it later).
SystemJS also supports dynamic loading of modules:
/ / Use SystemJS module with promise APIs. System.import (". / esCounterModule.js") .then (dynamicESCounterModule = > {dynamicESCounterModule.increase (); dynamicESCounterModule.reset ();})
Webpack module (packaged AMD,CJS,ESM)
Webpack is a powerful module packaging tool that converts and packages modules in AMD, CommonJS, and ES Module formats into a single JS file.
Babel module
Babel is also a converter that converts ES6+ code into an earlier version of ES. The counter module in the previous example is converted with Babel and the code looks like this:
/ / Babel. Object.defineProperty (exports, "_ esModule", {value: true}); exports ["default"] = void 0; function _ interopRequireDefault (obj) {return obj & & obj.__esModule? Obj: {"default": obj};} / / Define ES module: esCounterModule.js. Var dependencyModule1 = _ interopRequireDefault (require (". / amdDependencyModule1"); var dependencyModule2 = _ interopRequireDefault (require (". / commonJSDependencyModule2")); dependencyModule1 ["default"]. Api1 (); dependencyModule2 ["default"]. Api2 (); var count = 0; var increase = function () {return + + count;}; var reset = function () {count = 0; console.log ("Count is reset.");}; exports ["default"] = {increase: increase, reset: reset}
The index.js introduced into the module will be converted to:
/ / Babel. Function _ interopRequireDefault (obj) {return obj & & obj.__esModule? Obj: {"default": obj};} / / Use ES module: index.js var esCounterModule = _ interopRequireDefault (require (". / esCounterModule.js")); esCounterModule ["default"] .increase (); esCounterModule ["default"] .reset ()
The above is the default transformation behavior of Babel, which can also be used in conjunction with other plug-ins, such as SystemJS mentioned earlier. After configuration, Babel can convert AMD, CJS, ES Module into System module format.
TypeScript module
TypeScript is a superset of JavaScript and supports all JavaScript grammars, including ES6 module syntax. When converting, it can retain ES6 syntax, or it can be converted to AMD, CJS, UMD, SystemJS and other formats, depending on the configuration:
{"compilerOptions": {"module": "ES2020", / / None, CommonJS, AMD, System, UMD, ES6, ES2015, ES2020, ESNext }}
TypeScript also supports the module and namespace keywords, which represent internal modules.
Module Counter {let count = 0; export const increase = () = > + + count; export const reset = () = > {count = 0; console.log ("Count is reset.");} namespace Counter {let count = 0; export const increase = () = > + + count; export const reset = () = > {count = 0; console.log ("Count is reset.");};}
Can be converted to JavaScript objects:
Var Counter; (function (Counter) {var count = 0; Counter.increase = function () {return + + count;}; Counter.reset = function () {count = 0; console.log ("Count is reset.");};}) (Counter | (Counter = {}))
As standardization advances, both Node.js and the latest modern browsers begin to support the ES module format. If you want to use modularity in the old environment, you can convert it through tools such as Webpack, Babel, TypeScript, SystemJS, and so on.
About JavaScript modularization programs and tools are shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.