From d2b50123d485c68c5321339446cf77a4bb16dd82 Mon Sep 17 00:00:00 2001 From: Joshua Chen Date: Mon, 20 Jun 2022 20:20:22 +0800 Subject: [PATCH] Split dynamic import into its own page (#17402) * Split dynamic import into its own page * address reviews * add an example * minor tweak --- .../reference/operators/import/index.md | 144 ++++++++++++++++++ .../reference/statements/export/index.md | 8 +- .../reference/statements/import/index.md | 126 ++++----------- 3 files changed, 178 insertions(+), 100 deletions(-) create mode 100644 files/en-us/web/javascript/reference/operators/import/index.md diff --git a/files/en-us/web/javascript/reference/operators/import/index.md b/files/en-us/web/javascript/reference/operators/import/index.md new file mode 100644 index 000000000000000..7f9b9c3b925dcf8 --- /dev/null +++ b/files/en-us/web/javascript/reference/operators/import/index.md @@ -0,0 +1,144 @@ +--- +title: import +slug: Web/JavaScript/Reference/Operators/import +tags: + - ECMAScript 2015 + - JavaScript + - Language feature + - Modules + - Reference + - dynamic import + - import +browser-compat: javascript.operators.import +--- +{{jsSidebar("Operators")}} + +The `import()` call, commonly called _dynamic import_, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment. + +Unlike the [declaration-style counterpart](/en-US/docs/Web/JavaScript/Reference/Statements/import), dynamic imports are only evaluated when needed, and permits greater syntactic flexibility. + +## Syntax + +```js +import(moduleName) +``` + +The `import()` call is a syntax that closely resembles a function call, but `import` itself is a keyword, not a function. You cannot alias it like `const myImport = import`, which will throw a {{jsxref("SyntaxError")}}. + +### Parameters + +- `moduleName` + - : The module to import from. The evaluation of the specifier is host-specified, but always follows the same algorithm as static [import declarations](/en-US/docs/Web/JavaScript/Reference/Statements/import). + +### Return value + +It returns a promise which fulfills to an object containing all exports from `moduleName`, with the same shape as a namespace import (`import * as name from moduleName`): an object with `null` prototype, and the default export available as a key named `default`. + +## Description + +The import declaration syntax (`import something from "somewhere"`) is static and will always result in the imported module being evaluated at load time. Dynamic imports allows one to circumvent the syntactic rigidity of import declarations and load a module conditionally or on demand. The following are some reasons why you might need to use dynamic import: + +- When importing statically significantly slows the loading of your code and there is a low likelihood that you will need the code you are importing, or you will not need it until a later time. +- When importing statically significantly increases your program's memory usage and there is a low likelihood that you will need the code you are importing. +- When the module you are importing does not exist at load time. +- When the import specifier string needs to be constructed dynamically. (Static import only supports static specifiers.) +- When the module being imported has side effects, and you do not want those side effects unless some condition is true. (It is recommended not to have any side effects in a module, but you sometimes cannot control this in your module dependencies.) +- When you are in a non-module environment (for example, `eval` or a script file). + +Use dynamic import only when necessary. The static form is preferable for loading initial dependencies, and can benefit more readily from static analysis tools and [tree shaking](/en-US/docs/Glossary/Tree_shaking). + +If your file is not run as a module (if it's referenced in an HTML file, the script tag must have `type="module"`), you will not be able to use static import declarations, but the asynchronous dynamic import syntax will always be available, allowing you to import modules into non-module environments. + +## Examples + +### Import a module for its side effects only + +```js +(async () => { + if (somethingIsTrue) { + // import module for side effects + await import("/modules/my-module.js"); + } +})(); +``` + +If your project uses packages that export ESM, you can also import them for side +effects only. This will run the code in the package entry point file (and any files it +imports) only. + +### Importing defaults + +You need to destructure and rename the "default" key from the returned object. + +```js +(async () => { + if (somethingIsTrue) { + const { + default: myDefault, + foo, + bar, + } = await import("/modules/my-module.js"); + } +})(); +``` + +### Importing on-demand in response to user action + +This example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. This is not the only way to implement this functionality. The `import()` function also supports `await`. + +```js +const main = document.querySelector("main"); +for (const link of document.querySelectorAll("nav > a")) { + link.addEventListener("click", (e) => { + e.preventDefault(); + + import("/modules/my-module.js") + .then((module) => { + module.loadPageInto(main); + }) + .catch((err) => { + main.textContent = err.message; + }); + }); +} +``` + +### Importing different modules based on environment + +In processes such as server-side rendering, you may need to load different logic on server or in browser because they interact with different globals or modules (for example, browser code has access to web APIs like `document` and `navigator`, while server code has access to the server file system). You can do so through a conditional dynamic import. + +```js +let myModule; + +if (typeof window === "undefined") { + myModule = await import("module-used-on-server"); +} else { + myModule = await import("module-used-in-browser"); +} +``` + +### Importing modules with a non-literal specifier + +Dynamic imports allow any expression as the module specifier, not necessarily string literals. + +Here, we load 10 modules: `/modules/module-0.js`, `/modules/module-1.js`... in parallel, and call the `load` functions that each one exports. + +```js +Promise.all( + Array.from({ length: 10 }).map((_, index) => + import(`/modules/module-${index}.js`) + ) +).then((modules) => modules.forEach((module) => module.load())); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [`import` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/import) diff --git a/files/en-us/web/javascript/reference/statements/export/index.md b/files/en-us/web/javascript/reference/statements/export/index.md index 4b788372d62fac7..6f399a2b62e7779 100644 --- a/files/en-us/web/javascript/reference/statements/export/index.md +++ b/files/en-us/web/javascript/reference/statements/export/index.md @@ -13,10 +13,10 @@ browser-compat: javascript.statements.export --- {{jsSidebar("Statements")}} -The **`export`** statement is used +The **`export`** declaration is used when creating JavaScript modules to export live bindings to functions, objects, or primitive values from the module so they can be used by other programs with the -{{jsxref("Statements/import", "import")}} statement. The value of an imported binding +{{jsxref("Statements/import", "import")}} declaration. The value of an imported binding is subject to change in the module that exports it. When a module updates the value of a binding that it exports, the update will be visible in its imported value. @@ -42,6 +42,7 @@ export { name1, name2, …, nameN }; // Renaming exports export { variable1 as name1, variable2 as name2, …, nameN }; +export { variable1 as "string name" }; // Exporting destructured assignments with renaming export const { name1, name2: bar } = o; @@ -62,8 +63,7 @@ export { default, … } from …; ``` - `nameN` - - : Identifier to be exported (so that it can be imported via - {{jsxref("Statements/import", "import")}} in another script). + - : Identifier to be exported (so that it can be imported via {{jsxref("Statements/import", "import")}} in another script). If you use an alias with `as`, the actual exported name can be specified as a string literal, which may not be a valid identifier. ## Description diff --git a/files/en-us/web/javascript/reference/statements/import/index.md b/files/en-us/web/javascript/reference/statements/import/index.md index 4dccd8597a3de1e..9bc579bbd6859c1 100644 --- a/files/en-us/web/javascript/reference/statements/import/index.md +++ b/files/en-us/web/javascript/reference/statements/import/index.md @@ -14,9 +14,7 @@ browser-compat: javascript.statements.import --- {{jsSidebar("Statements")}} -The static **`import`** statement is -used to import read-only live bindings which are [exported](/en-US/docs/Web/JavaScript/Reference/Statements/export) by -another module. +The static **`import`** declaration is used to import read-only live bindings which are [exported](/en-US/docs/Web/JavaScript/Reference/Statements/export) by another module. Imported modules are in {{JSxRef("Strict_mode","strict mode")}} whether you declare them as such or not. The `import` statement cannot be @@ -24,8 +22,7 @@ used in embedded scripts unless such script has a `type="module"`. Bindings imported are called live bindings because they are updated by the module that exported the binding. -There is also a function-like dynamic **`import()`**, which -does not require scripts of `type="module"`. +There is also a function-like dynamic [`import()`](/en-US/docs/Web/JavaScript/Reference/Operators/import), which does not require scripts of `type="module"`. Backward compatibility can be ensured using attribute `nomodule` on the {{HTMLElement("script")}} tag. @@ -37,28 +34,25 @@ import defaultExport from "module-name"; import * as name from "module-name"; import { export1 } from "module-name"; import { export1 as alias1 } from "module-name"; +import { default as alias } from "module-name"; import { export1 , export2 } from "module-name"; import { export1 , export2 as alias2 , [...] } from "module-name"; +import { "string name" as alias } from "module-name"; import defaultExport, { export1 [ , [...] ] } from "module-name"; import defaultExport, * as name from "module-name"; import "module-name"; -var promise = import("module-name"); ``` - `defaultExport` - - : Name that will refer to the default export from the module. + - : Name that will refer to the default export from the module. Must be a valid JavaScript identifier. - `module-name` - - : The module to import from. This is often a relative or absolute URL to the - `.js` file containing the module. Certain bundlers may permit or require - the use of the extension; check your environment. Only single quoted and double - quoted Strings are allowed. + - : The module to import from. The evaluation of the specifier is host-specified. This is often a relative or absolute URL to the `.js` file containing the module. In Node, extension-less imports often refer to packages in `node_modules`. Certain bundlers may permit importing files without extensions; check your environment. Only single quoted and double quoted Strings are allowed. - `name` - - : Name of the module object that will be used as a kind of namespace when referring to - the imports. + - : Name of the module object that will be used as a kind of namespace when referring to the imports. Must be a valid JavaScript identifier. - `exportN` - - : Name of the exports to be imported. + - : Name of the exports to be imported. The name can be either an identifier or a string literal, depending on what `module-name` declares to export. If it is a string literal, it must be aliased to a valid identifier. - `aliasN` - - : Names that will refer to the named imports. + - : Names that will refer to the named imports. Must be a valid JavaScript identifier. ## Description @@ -67,6 +61,10 @@ as a kind of namespace to refer to the exports. The `export` parameters specify individual named exports, while the `import * as name` syntax imports all of them. Below are examples to clarify the syntax. +`import` declarations are only permitted at the top-level of modules, and can only be present in module files. If an `import` declaration is encountered in non-module contexts (for example, script files, `eval`, `new Function`, which all have "script" or "function" as parsing goals), a `SyntaxError` is thrown. To load modules in non-module contexts, use the [dynamic import](/en-US/docs/Web/JavaScript/Reference/Operators/import) syntax instead. + +`import` declarations are designed to be syntactically rigid (for example, only string literal specifiers, only permitted at top-level, all bindings must be identifiers...), which allows modules to be statically analyzed and synchronously linked before getting evaluated. This is the key to making modules asynchronous by nature, powering features like [top-level await](/en-US/docs/Web/JavaScript/Guide/Modules#top_level_await). + ### Import an entire module's contents This inserts `myModule` into the current scope, containing all the exports @@ -84,6 +82,8 @@ namespace. For example, if the module imported above includes an export myModule.doAllTheAmazingThings(); ``` +`myModule` is an object with `null` prototype, and the default export will be available as a key called `default`. + ### Import a single export from a module Given an object or value named `myExport` which has been exported from the @@ -114,6 +114,18 @@ import {reallyReallyLongModuleExportName as shortName} from '/modules/my-module.js'; ``` +A module may also export a member as a string literal which is not a valid identifier, in which case you must alias it in order to use it in the current module. + +```js +// /modules/my-module.js +const a = 1; +export { a as "a-b" }; +``` + +```js +import { "a-b" as a } from "/modules/my-module.js"; +``` + ### Rename multiple exports during import Import multiple exports from a module with convenient aliases. @@ -134,17 +146,6 @@ the module's global code, but doesn't actually import any values. import '/modules/my-module.js'; ``` -This works with [dynamic imports](#dynamic_imports) as well: - -```js -(async () => { - if (somethingIsTrue) { - // import module for side effects - await import('/modules/my-module.js'); - } -})(); -``` - If your project uses packages that export ESM, you can also import them for side effects only. This will run the code in the package entry point file (and any files it imports) only. @@ -177,54 +178,10 @@ import myDefault, {foo, bar} from '/modules/my-module.js'; // specific, named imports ``` -When importing a default export with [dynamic imports](#dynamic_imports), it -works a bit differently. You need to destructure and rename the "default" key from the -returned object. - -```js -(async () => { - if (somethingIsTrue) { - const { default: myDefault, foo, bar } = await import('/modules/my-module.js'); - } -})(); -``` - -### Dynamic Imports - -The standard import syntax is static and will always result in all code in the imported -module being evaluated at load time. In situations where you wish to load a module -conditionally or on demand, you can use a dynamic import instead. The following are some -reasons why you might need to use dynamic import: - -- When importing statically significantly slows the loading of your code and there is - a low likelihood that you will need the code you are importing, or you will not need - it until a later time. -- When importing statically significantly increases your program's memory usage and - there is a low likelihood that you will need the code you are importing. -- When the module you are importing does not exist at load time -- When the import specifier string needs to be constructed dynamically. (Static import - only supports static specifiers.) -- When the module being imported has side effects, and you do not want those side - effects unless some condition is true. (It is recommended not to have any side effects - in a module, but you sometimes cannot control this in your module dependencies.) - -Use dynamic import only when necessary. The static form is preferable for loading -initial dependencies, and can benefit more readily from static analysis tools and [tree shaking](/en-US/docs/Glossary/Tree_shaking). - -To dynamically import a module, the `import` keyword may be called as a -function. When used this way, it returns a promise. - -```js -import('/modules/my-module.js') - .then((module) => { - // Do something with the module. - }); -``` - -This form also supports the `await` keyword. +Importing a name called `default` has the same effect as a default import. It is necessary to alias the name because `default` is a reserved word. ```js -let module = await import('/modules/my-module.js'); +import { default as myDefault } from '/modules/my-module.js'; ``` ## Examples @@ -260,30 +217,6 @@ getUsefulContents('http://www.example.com', data => { doSomethingUseful(data); }); ``` -### Dynamic Import - -This example shows how to load functionality on to a page based on a user action, in -this case a button click, and then call a function within that module. This is not the -only way to implement this functionality. The `import()` function also -supports `await`. - -```js -const main = document.querySelector("main"); -for (const link of document.querySelectorAll("nav > a")) { - link.addEventListener("click", e => { - e.preventDefault(); - - import('/modules/my-module.js') - .then(module => { - module.loadPageInto(main); - }) - .catch(err => { - main.textContent = err.message; - }); - }); -} -``` - ## Specifications {{Specifications}} @@ -295,6 +228,7 @@ for (const link of document.querySelectorAll("nav > a")) { ## See also - {{JSxRef("Statements/export", "export")}} +- [Dynamic imports](/en-US/docs/Web/JavaScript/Reference/Operators/import) - [`import.meta`](/en-US/docs/Web/JavaScript/Reference/Statements/import.meta) - Limin Zhu, Brian Terlson and Microsoft Edge Team: [Previewing ES6 Modules and more from ES2015, ES2016 and beyond](https://blogs.windows.com/msedgedev/2016/05/17/es6-modules-and-beyond/)