惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
D
Docker
GbyAI
GbyAI
B
Blog RSS Feed
博客园 - 司徒正美
博客园 - Franky
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
AI
AI
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
S
Secure Thoughts
博客园 - 聂微东
L
LINUX DO - 最新话题
U
Unit 42
SecWiki News
SecWiki News
A
Arctic Wolf
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Visual Studio Blog
量子位
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
大猫的无限游戏
大猫的无限游戏
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
B
Blog
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
Last Week in AI
Last Week in AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
Latest news
Latest news

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
ES Modules Dynamic Import
Dmitri Pavlutin · 2021-06-11 · via Dmitri Pavlutin Blog
Post cover

ES modules are a way to organize cohesive chunks of code in JavaScript. Here's a simple ES module:


// An ES module

import { concat } from './concatModule.js';

concat('a', 'b'); // => 'ab'


import { concat } from './concatModule.js' is considered a static import.

Static importing works in most situations. But sometimes to save client's bandwidth you may choose to load the modules dynamically.

You can import ES modules dynamically if you use import as a function — import(pathToModule) — a feature available starting ES2020.

Let's see how ES modules' dynamic import works, and when it's useful.

1. Dynamic importing

When the import keyword is used as a function:


const module = await import(path);


import(path) returns a promise and starts an asynchronous task to load the module located at path. If the module is loaded successfully, then the promise resolves to the module content, otherwise, the promise rejects.

path can be any expression that evaluates to a string denoting a path. Valid path expressions are:


// Classic string literals

const module1 = await import('./myModule.js');

// A variable

const path = './myOtherModule.js';

const module2 = await import(path);

// Function call

const getPath = (version) => `./myModule/versions/${version}.js`;

const moduleVersion1 = await import(getPath('v1.0'));

const moduleVersion2 = await import(getPath('v2.0'));


import(path), returning a promise, works great with the async/await syntax. For example, let's load a module inside of an asynchronous function:


async function loadMyModule() {

const myModule = await import('./myModule.js');

// ... use myModule

}

loadMyModule();


Now, knowing how to load the module, let's extract components (default or named) from the imported module.

2. Importing components

2.1 Dynamic import of named

Let's consider the following module, named namedConcat.js:


// namedConcat.js

export const concat = (paramA, paramB) => paramA + paramB;


namedConcat performs a named export of concat function.

To dynamically import namedConcat.js, and access the named export concat, then destructure the resolved module object by the named export:


async function loadMyModule() {

const { concat } = await import('./namedConcat.js');

concat('b', 'c'); // => 'bc'

}

loadMyModule();


2.2 Dynamic import of default

To dynamically import a default, just read the default property from the module object.

Let's say that defaultConcat.js exports the function as a default export:


// defaultConcat.js

export default (paramA, paramB) => paramA + paramB;


When importing defaultConcat.js dynamically, and specifically accessing the default export, just read the default property.

But there's a nuance. default is a keyword in JavaScript, so it cannot be used as a variable name. What you do is use destructuring with aliasing:


async function loadMyModule() {

const { default: defaultFunc } = await import('./defaultConcat.js');

defaultFunc('b', 'c'); // => 'bc'

}

loadMyModule();


2.3 Dynamic import of mixed content

If the imported module exports default and multiple named exports, then you can access all these components using a single destructuring:


async function loadMyModule() {

const {

default: defaultImport,

namedExport1,

namedExport2

} = await import('./mixedExportModule.js');

// ...

}

loadMyModule();


3. When to use dynamic import

I recommend using dynamic import when importing big modules conditionally:

  • you might use the module from time to time, depending on runtime conditions
  • you might want to load different versions of a big module, also depending on runtime conditions.

For example:


async function execBigModule(condition) {

if (condition) {

const { funcA } = await import('./bigModuleA.js');

funcA();

} else {

const { funcB } = await import('./bigModuleB.js');

funcB();

}

}

execBigModule(true);


For small modules (like namedConcat.js or defaultConcat.js from the previous example), that have a few lines of code, the dynamic import doesn't worth the hassle.

4. Conclusion

To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module.

const module = await import(path) returns a promise that resolves to an object containing the components of the imported module.

In that object, the default property contains the default export, and the named exports are contained in the corresponding properties:


const {

default: defaultComponent,

namedExport1,

namedExport2

} = await import(path);


The dynamic import is supported by both Node.js (version 13.2 and above) and most modern browsers.

What other interesting use cases of the dynamic import do you know? Share your idea in a comment below!

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉, developing a gift boxes Shopify app, and blogging about Shopify. Living in the sunny Barcelona. 🇪🇸