Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the ECMAScript module

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "how to use the ECMAScript module", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use the ECMAScript module" article.

What is an ES module?

The ECMAScript module (referred to as the ES module) is a mechanism for code reuse in JavaScript introduced in 2015. In the highly fragmented JavaScript module scenario, it finally became the standard.

Until 2015, JavaScript did not have a standard code reuse mechanism. There have been many attempts at standardization in this area, which has led to a mess of fragmentation over the years.

You may have heard of the AMD module, UMD, or CommonJS. There is no obvious winner. Finally, with the landing language of the ECMAScript 2015 des module.

We now have an "official" module system.

ECMAScript modules are everywhere?

In theory, the ECMAScript module should be universally applicable to all JavaScript environments. In fact, browsers are still the main target of the ES module.

In May 2020, when Node.js v12.17.0 shipped, the ECMAScript module was supported with no logo. This means that we can now use import and export in Node.js without any additional command-line flags.

There is still a long way to go before the ECMAScript module works in any JavaScript environment, but it is going in the right direction.

What is the ES module like?

An ES module is a simple file, and we can declare one or more exits. Take this fictional utils.js as an example.

/ / utils.jsexport function funcA () {return "Hello named export!";} export default function funcB () {return "Hello default export!";}

We have two exporters here.

The first is a named export, followed by a default export, represented as an export default.

Assuming that this file named utils.js lives in our project folder, we can import the objects provided by this module in another file.

How to import from an ES module

Suppose we also have a file named consumer.js in the project folder. To import the functions exposed by utils.js, we can do this.

/ / consumer.jsimport {funcA} from ". / util.js"

This syntax is a named import method, which is similar to the named export method.

If you want to import a funcB defined as the default export, we can do this:

/ / consumer.jsimport funcB from ". / util.js"

If we want to import both default and named exports in the same file, we can compress them as follows:

/ / consumer.jsimport funcB, {funcA} from ". / util.js"; funcB (); funcA ()

We can also import the entire module using star.

Import * as myModule from ". / util.js"; myModule.funcA (); myModule.default ()

Note that in this case, the default export must be explicitly called.

To import from a remote module.

Import {createStore} from "https://unpkg.com/redux@4.0.5/es/redux.mjs";const store = ECMAScript module in createStore (/ * do stuff * /) browser

Modern browsers support the ES module, although there are some considerations. To load a module, add the module to the type attribute of the script tag.

ECMAScript modules in the browserThe result is:

Import {appendResult} from ". / myModule.js"; const el = document.getElementById ("el"); appendResult (el)

Here myModule.js is a simple module under the same project folder.

Export function appendResult (element) {const result = Math.random (); element.innerText + = result;}

Although the ES module can be used directly in browsers, the task of bundling JavaScript applications is still exclusive to tools such as webpack for maximum flexibility, code splitting, and compatibility with older browsers.

Dynamic import

The ES module is static, which means that we cannot change the import at run time. With dynamic import logged in in 2020, we can dynamically load our code based on user interaction (webpack provided dynamic import functionality before ECMAScript 2020).

Consider a simple HTML that can load a script.

Dynamic importsLoad!

You can also consider using several exported JavaScript modules.

/ / util.jsexport function funcA () {console.log ("Hello named export!");} export default function funcB () {console.log ("Hello default export!");}

If you want to load this module dynamically, maybe click on it, and we can do so.

/ loader.jsconst btn = document.getElementById ("btn"); btn.addEventListener ("click", () = > {/ / loads named export import (". / util.js"). Then (({funcA}) = > {funcA ();});})

Here, we load only named exports by refactoring the module's objects.

({funcA}) = > {}

ES modules are actually JavaScript objects: we can ReFactor their properties or call any of their exposed methods.

To dynamically import a default export, we can do this.

/ / loader.jsconst btn = document.getElementById ("btn"); btn.addEventListener ("click", () = > {/ / loads entire module / / runs default export import (". / util.js"). Then ((module) = > {module.default ();});})

When importing a module as a whole, we can use all of its output.

/ / loader.jsconst btn = document.getElementById ("btn"); btn.addEventListener ("click", () = > {/ / loads entire module / / uses everything import (". / util.js"). Then ((module) = > {module.funcA (); module.default ();});})

There is also a common way of dynamic import, where we extract logic at the top of the file.

Const loadUtil = () = > import (". / util.js"); const btn = document.getElementById ("btn"); btn.addEventListener ("click", () = > {/ /})

Here, loadUtil will return a Promise, ready for chaining.

Const loadUtil = () = > import (". / util.js"); const btn = document.getElementById ("btn"); btn.addEventListener ("click", () = > {loadUtil (). Then (module = > {module.funcA (); module.default ();})

Dynamic imports look good, but what's the use of them?

Through dynamic import, we can split our code and load only important content at the right time. Before dynamic import and login to JavaScript, this mode is exclusive to webpack, the module bundler.

Front-end libraries such as React and Vue make extensive use of code splitting through dynamic imports, loading chunked code in response to events, such as user interaction or routing changes.

Dynamic Import of JSON Files

Suppose you have a JSON file, person.json, somewhere in the code base.

{"name": "Jules", "age": 43}

Now, you want to import this file dynamically in response to some user interactions.

Since the JSON file exports only a default export, it is not a function, so you can only access the default export like this.

Const loadPerson = () = > import (". / person.json"); const btn = document.getElementById ("btn"); btn.addEventListener ("click", () = > {loadPerson (). Then (module = > {const {name, age} = module.default; console.log (name, age);});})

Here, we ReFactor name and age from the default export.

Const {name, age} = module.default; dynamic import using async/await

The import () statement always returns a Promise, which means we can use async/await on it.

Const loadUtil = () = > import (". / util.js"); const btn = document.getElementById ("btn"); btn.addEventListener ("click", async () = > {const utilsModule = await loadUtil (); utilsModule.funcA (); utilsModule.default ();})

Dynamic Import name

When importing a module with import (), you can name it whatever you want, as long as it is consistent.

Import (". / util.js") .then ((module) = > {module.funcA (); module.default ();})

Or:

Import (". / util.js"). Then ((utilModule) = > {utilModule.funcA (); utilModule.default ();}); the above is about the content of this article "how to use the ECMAScript module". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report