ES6 module: Modular solution for modern JavaScript
This article explores ES6 modules and shows how to use them with the help of a translator. Almost all languages ??have the concept of modules—a way to include declared functions in another file. Typically, developers create a packaged code base that handles related tasks. The library can be referenced by an application or other module. The advantages are:
- The code can be split into smaller, self-contained files.
- The same module can be shared among any number of applications.
- Ideally, modules do not need to be checked by other developers as they have been proven to be effective.
- The code that references the module knows that it is a dependency. If the module file is changed or moved, the problem will appear immediately.
- Module code (usually) helps to eliminate naming conflicts. The function x() in module 1 does not conflict with the function x() in module 2. You can use options such as namespace to change calls to module1.x() and module2.x().
Where are modules in JavaScript?
Anyone who started web development a few years ago would be surprised to find that there is no concept of modules in JavaScript. It is impossible to directly reference or include a JavaScript file into another file. Therefore, developers turn to other methods.
Various HTML
Functions may override other functions unless appropriate module mode is used. Early JavaScript libraries were notorious for using global function names or overwriting native methods.
Or inline:
<p>
</p>
<ul></ul>
Script merge
<??>
Solve multiple
</pre>
<p>
<strong>
</strong>
HTML 可以使用多個 <script>
標(biāo)簽加載任意數(shù)量的 JavaScript 文件:
<script src="lib1.js"></script>Modules must be served using MIME type application/javascript. Most servers do this automatically, but be careful about dynamically generated scripts or .mjs files (see the Node.js section below). Regular <script src="lib2.js"></script><script src="core.js"></script> <script>console.log('inline code');</script><script></code> 標(biāo)簽問題的一種方法是將所有 JavaScript 文件合并成一個大型文件。這解決了一些性能和依賴項(xiàng)管理問題,但可能會導(dǎo)致手動構(gòu)建和測試步驟。</p> <p><strong>模塊加載器</strong></p> <p>RequireJS 和 SystemJS 等系統(tǒng)提供了一個庫,用于在運(yùn)行時(shí)加載和命名其他 JavaScript 庫。模塊在需要時(shí)使用 Ajax 方法加載。這些系統(tǒng)有所幫助,但對于大型代碼庫或添加標(biāo)準(zhǔn) <code><script></code> 標(biāo)簽的網(wǎng)站來說,可能會變得復(fù)雜。</p> <p><strong>模塊打包器、預(yù)處理器和轉(zhuǎn)譯器</strong></p> <p>打包器引入了編譯步驟,以便在構(gòu)建時(shí)生成 JavaScript 代碼。代碼經(jīng)過處理以包含依賴項(xiàng)并生成單個 ES5 跨瀏覽器兼容的合并文件。流行的選項(xiàng)包括 Babel、Browserify、webpack 以及更通用的任務(wù)運(yùn)行器,如 Grunt 和 Gulp。</p> <p>JavaScript 構(gòu)建過程需要一些努力,但也有好處:</p> <ul> <li>處理是自動化的,因此人為錯誤的可能性較小。</li> <li>進(jìn)一步的處理可以整理代碼、刪除調(diào)試命令、縮小結(jié)果文件等。</li> <li>轉(zhuǎn)譯允許您使用替代語法,如 TypeScript 或 CoffeeScript。</li> </ul> <p><strong>ES6 模塊</strong></p> <p>上述選項(xiàng)引入了各種相互競爭的模塊定義格式。廣泛采用的語法包括:</p> <ul> <li>CommonJS——Node.js 中使用的 module.exports 和 require 語法</li> <li>異步模塊定義 (AMD)</li> <li>通用模塊定義 (UMD)</li> </ul> <p>因此,在 ES6 (ES2015) 中提出了單一的原生模塊標(biāo)準(zhǔn)。</p> <p>ES6 模塊內(nèi)部的所有內(nèi)容默認(rèn)情況下都是私有的,并且在嚴(yán)格模式下運(yùn)行(不需要“use strict”)。公共變量、函數(shù)和類使用 export 導(dǎo)出。例如:</p> <pre class="brush:php;toolbar:false"><code class="javascript">// lib.js export const PI = 3.1415926; export function sum(...args) { log('sum', args); return args.reduce((num, tot) => tot + num); } export function mult(...args) { log('mult', args); return args.reduce((num, tot) => tot * num); } // 私有函數(shù) function log(...msg) { console.log(...msg); }
或者,可以使用單個 export 語句。例如:
// lib.js const PI = 3.1415926; function sum(...args) { log('sum', args); return args.reduce((num, tot) => tot + num); } function mult(...args) { log('mult', args); return args.reduce((num, tot) => tot * num); } // 私有函數(shù) function log(...msg) { console.log(...msg); } export { PI, sum, mult };
然后使用 import 將模塊中的項(xiàng)目導(dǎo)入到另一個腳本或模塊中:
// main.js import { sum } from './lib.js'; console.log(sum(1, 2, 3, 4)); // 10
在這種情況下,lib.js 與 main.js 在同一個文件夾中??梢允褂媒^對文件引用(以 / 開頭)、相對文件引用(以 ./ 或 ../ 開頭)或完整 URL。可以一次導(dǎo)入多個項(xiàng)目:
import { sum, mult } from './lib.js'; console.log(sum(1, 2, 3, 4)); // 10 console.log(mult(1, 2, 3, 4)); // 24
并且可以為導(dǎo)入指定別名以解決命名沖突:
import { sum as addAll, mult as multiplyAll } from './lib.js'; console.log(addAll(1, 2, 3, 4)); // 10 console.log(multiplyAll(1, 2, 3, 4)); // 24
最后,可以通過提供命名空間來導(dǎo)入所有公共項(xiàng)目:
import * as lib from './lib.js'; console.log(lib.PI); // 3.1415926 console.log(lib.sum(1, 2, 3, 4)); // 10 console.log(lib.mult(1, 2, 3, 4)); // 24
在瀏覽器中使用 ES6 模塊
在撰寫本文時(shí),ES6 模塊受 Chromium 系瀏覽器 (v63+)、Safari 11+ 和 Edge 16+ 支持。Firefox 支持將在版本 60 中到來(在 v58+ 中位于 about:config 標(biāo)志之后)。使用模塊的腳本必須通過在 <script>
標(biāo)簽中設(shè)置 type="module" 屬性來加載。例如:
Module rollback<script>
標(biāo)簽可以獲取其他域上的腳本,但模塊是使用跨域資源共享 (CORS) 獲取的。因此,不同域上的模塊必須設(shè)置適當(dāng)?shù)?HTTP 標(biāo)頭,例如 Access-Control-Allow-Origin: *。最后,除非在
<script>
標(biāo)簽中添加 crossorigin="use-credentials" 屬性并且響應(yīng)包含標(biāo)頭 Access-Control-Allow-Credentials: true,否則模塊不會發(fā)送 Cookie 或其他標(biāo)頭憑據(jù)。模塊執(zhí)行被延遲
<script>
標(biāo)簽的defer
屬性會延遲腳本執(zhí)行,直到文檔加載并解析完畢。模塊(包括內(nèi)聯(lián)腳本)默認(rèn)情況下會延遲。示例:Browsers that do not support modules will not run the type="module" script. You can use the nomodule property to provide a fallback script that is ignored by the module-compatible browser. For example:
<??>Should you use modules in your browser?
Browser support is growing, but it may be too early to switch to the ES6 module. Currently, it is best to use a module packer to create a script that works anywhere.
Using ES6 module in Node.js
Node.js was released in 2009, it was unimaginable that no module was provided at any runtime. CommonJS is used, which means that the Node package manager npm can be developed. Since then, usage has increased exponentially. The CommonJS module is encoded in a similar way to the ES2015 module. Use module.exports instead of export:
<??> <??>Use require (rather than import) to import this module into another script or module:
// lib.js const PI = 3.1415926; function sum(...args) { log('sum', args); return args.reduce((num, tot) => tot + num); } function mult(...args) { log('mult', args); return args.reduce((num, tot) => tot * num); } // 私有函數(shù) function log(...msg) { console.log(...msg); } module.exports = { PI, sum, mult };require can also import all projects:
const { sum, mult } = require('./lib.js'); console.log(sum(1, 2, 3, 4)); // 10 console.log(mult(1, 2, 3, 4)); // 24So, it's easy to implement ES6 modules in Node.js, right? Not right. The ES6 module is located after the flags in Node.js 9.8.0 and will not be fully implemented until at least version 10. Although CommonJS and ES6 modules have similar syntax, they work in a fundamentally different way:
- ES6 modules are pre-parsed before executing the code to parse further imports.
- The CommonJS module loads dependencies on demand when executing code.
In the example above, this does not make any difference, but consider the following ES2015 module code:
const lib = require('./lib.js'); console.log(lib.PI); // 3.1415926 console.log(lib.sum(1, 2, 3, 4)); // 10 console.log(lib.mult(1, 2, 3, 4)); // 24Output of ES2015:
// ES2015 模塊 // --------------------------------- // one.js console.log('running one.js'); import { hello } from './two.js'; console.log(hello); // --------------------------------- // two.js console.log('running two.js'); export const hello = 'Hello from two.js';Similar code written using CommonJS:
<code>running two.js running one.js Hello from two.js</code>Output of CommonJS:
// CommonJS 模塊 // --------------------------------- // one.js console.log('running one.js'); const hello = require('./two.js'); console.log(hello); // --------------------------------- // two.js console.log('running two.js'); module.exports = 'Hello from two.js';Execution order can be critical in some applications, what happens if you mix ES2015 and CommonJS modules in the same file? To solve this problem, Node.js only allows the use of ES6 modules in files with the extension .mjs. Files with the extension .js will default to CommonJS. This is a simple option that removes most of the complexity and should help with the code editor and code inspector.
Should you use the ES6 module in Node.js?
ES6 module is only useful in Node.js v10 and later (released in April 2018). Converting an existing project is unlikely to bring any benefits and will make the application incompatible with earlier versions of Node.js. For new projects, the ES6 module provides an alternative to CommonJS. The syntax is the same as client encoding and may provide an easier way to isomorphic JavaScript, which can run on a browser or server.
Module Melee
The standardized JavaScript module system took years to emerge and took longer to implement, but the problem has been corrected. Starting in mid-2018, all mainstream browsers and Node.js support the ES6 module, although a switching delay should be expected when everyone upgrades. Learn ES6 modules today to benefit from your JavaScript development tomorrow.
FAQs about ES6 modules (FAQ)
(The FAQ part in the original document is omitted here because the full text has been fully pseudo-originalized)
The above is the detailed content of Understanding ES6 Modules. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.
