SOLFIND
Web Lens
Portal home

Modules: ECMAScript modules | Node.js v21.7.3 Documentation

https://nodejs.org/docs/latest-v21.x/api/esm.html • 92 KB fetched
Open original page


Modules: ECMAScript modules | Node.js v21.7.3 Documentation Node.js * About this documentation * Usage and example * Assertion testing * Asynchronous context tracking * Async hooks * Buffer * C++ addons * C/C++ addons with Node-API * C++ embedder API * Child processes * Cluster * Command-line options * Console * Corepack * Crypto * Debugger * Deprecated APIs * Diagnostics Channel * DNS * Domain * Errors * Events * File system * Globals * HTTP * HTTP/2 * HTTPS * Inspector * Internationalization * Modules: CommonJS modules * Modules: ECMAScript modules * Modules: node:module API * Modules: Packages * Net * OS * Path * Performance hooks * Permissions * Process * Punycode * Query strings * Readline * REPL * Report * Single executable applications * Stream * String decoder * Test runner * Timers * TLS/SSL * Trace events * TTY * UDP/datagram * URL * Utilities * V8 * VM * WASI * Web Crypto API * Web Streams API * Worker threads * Zlib * Code repository and issue tracker Node.js v21.7.3 documentation * Node.js v21.7.3 * ► ▼ Table of contents * Modules: ECMAScript modules * Introduction * Enabling * Packages * import Specifiers * Terminology * Mandatory file extensions * URLs * file: URLs * data: imports * node: imports * Import attributes * Builtin modules * import() expressions * import.meta * import.meta.dirname * import.meta.filename * import.meta.url * import.meta.resolve(specifier) * Interoperability with CommonJS * import statements * require * CommonJS Namespaces * Differences between ES modules and CommonJS * No require , exports , or module.exports * No __filename or __dirname * No Addon Loading * No require.resolve * No NODE_PATH * No require.extensions * No require.cache * JSON modules * Wasm modules * Top-level await * HTTPS and HTTP imports * Imports are limited to HTTP/1 * HTTP is limited to loopback addresses * Authentication is never sent to the destination server. * CORS is never checked on the destination server * Cannot load non-network dependencies * Network-based loading is not enabled by default * Loaders * Resolution and loading algorithm * Features * Resolution algorithm * Resolution Algorithm Specification * Customizing ESM specifier resolution algorithm * ► ▼ Index * About this documentation * Usage and example * Index * Assertion testing * Asynchronous context tracking * Async hooks * Buffer * C++ addons * C/C++ addons with Node-API * C++ embedder API * Child processes * Cluster * Command-line options * Console * Corepack * Crypto * Debugger * Deprecated APIs * Diagnostics Channel * DNS * Domain * Errors * Events * File system * Globals * HTTP * HTTP/2 * HTTPS * Inspector * Internationalization * Modules: CommonJS modules * Modules: ECMAScript modules * Modules: node:module API * Modules: Packages * Net * OS * Path * Performance hooks * Permissions * Process * Punycode * Query strings * Readline * REPL * Report * Single executable applications * Stream * String decoder * Test runner * Timers * TLS/SSL * Trace events * TTY * UDP/datagram * URL * Utilities * V8 * VM * WASI * Web Crypto API * Web Streams API * Worker threads * Zlib * Code repository and issue tracker * ► ▼ Other versions * 21.x * 20.x LTS * 19.x * 18.x LTS * 17.x * 16.x * 15.x * 14.x * 13.x * 12.x * 11.x * 10.x * 9.x * 8.x * ► ▼ Options * View on single page * View as JSON * Edit on GitHub Table of contents * Modules: ECMAScript modules * Introduction * Enabling * Packages * import Specifiers * Terminology * Mandatory file extensions * URLs * file: URLs * data: imports * node: imports * Import attributes * Builtin modules * import() expressions * import.meta * import.meta.dirname * import.meta.filename * import.meta.url * import.meta.resolve(specifier) * Interoperability with CommonJS * import statements * require * CommonJS Namespaces * Differences between ES modules and CommonJS * No require , exports , or module.exports * No __filename or __dirname * No Addon Loading * No require.resolve * No NODE_PATH * No require.extensions * No require.cache * JSON modules * Wasm modules * Top-level await * HTTPS and HTTP imports * Imports are limited to HTTP/1 * HTTP is limited to loopback addresses * Authentication is never sent to the destination server. * CORS is never checked on the destination server * Cannot load non-network dependencies * Network-based loading is not enabled by default * Loaders * Resolution and loading algorithm * Features * Resolution algorithm * Resolution Algorithm Specification * Customizing ESM specifier resolution algorithm Modules: ECMAScript modules # History Version Changes v21.0.0 Add experimental support for import attributes. v20.0.0 Module customization hooks are executed off the main thread. v18.6.0, v16.17.0 Add support for chaining module customization hooks. v17.1.0, v16.14.0 Add experimental support for import assertions. v17.0.0, v16.12.0 Consolidate customization hooks, removed getFormat , getSource , transformSource , and getGlobalPreloadCode hooks added load and globalPreload hooks allowed returning format from either resolve or load hooks. v14.8.0 Unflag Top-Level Await. v15.3.0, v14.17.0, v12.22.0 Stabilize modules implementation. v14.13.0, v12.20.0 Support for detection of CommonJS named exports. v14.0.0, v13.14.0, v12.20.0 Remove experimental modules warning. v13.2.0, v12.17.0 Loading ECMAScript modules no longer requires a command-line flag. v12.0.0 Add support for ES modules using .js file extension via package.json "type" field. v8.5.0 Added in: v8.5.0 Stability: 2 - Stable Introduction # ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements. The following example of an ES module exports a function: // addTwo.mjs function addTwo ( num ) { return num + 2 ; } export { addTwo }; copy The following example of an ES module imports the function from addTwo.mjs : // app.mjs import { addTwo } from './addTwo.mjs' ; // Prints: 6 console . log ( addTwo ( 4 )); copy Node.js fully supports ECMAScript modules as they are currently specified and provides interoperability between them and its original module format, CommonJS . Enabling # Node.js has two module systems: CommonJS modules and ECMAScript modules. Authors can tell Node.js to interpret JavaScript as an ES module via the .mjs file extension, the package.json "type" field with a value "module" , the --input-type flag with a value of "module" , or the --experimental-default-type flag with a value of "module" . These are explicit markers of code being intended to run as an ES module. Inversely, authors can tell Node.js to interpret JavaScript as CommonJS via the .cjs file extension, the package.json "type" field with a value "commonjs" , the --input-type flag with a value of "commonjs" , or the --experimental-default-type flag with a value of "commonjs" . When code lacks explicit markers for either module system, Node.js will inspect the source code of a module to look for ES module syntax. If such syntax is found, Node.js will run the code as an ES module; otherwise it will run the module as CommonJS. See Determining module system for more details. Packages # This section was moved to Modules: Packages . import Specifiers # Terminology # The specifier of an import statement is the string after the from keyword, e.g. 'node:path' in import { sep } from 'node:path' . Specifiers are also used in export from statements, and as the argument to an import() expression. There are three types of specifiers: * Relative specifiers like './startup.js' or '../config.mjs' . They refer to a path relative to the location of the importing file. The file extension is always necessary for these. * Bare specifiers like 'some-package' or 'some-package/shuffle' . They can refer to the main entry point of a package by the package name, or a specific feature module within a package prefixed by the package name as per the examples respectively. Including the file extension is only necessary for packages without an "exports" field. * Absolute specifiers like 'file:///opt/nodejs/config.js' . They refer directly and explicitly to a full path. Bare specifier resolutions are handled by the Node.js module resolution and loading algorithm . All other specifier resolutions are always only resolved with the standard relative URL resolution semantics. Like in CommonJS, module files within packages can be accessed by appending a path to the package name unless the package's package.json contains an "exports" field, in which case files within packages can only be accessed via the paths defined in "exports" . For details on these package resolution rules that apply to bare specifiers in the Node.js module resolution, see the packages documentation . Mandatory file extensions # A file extension must be provided when using the import keyword to resolve relative or absolute specifiers. Directory indexes (e.g. './startup/index.js' ) must also be fully specified. This behavior matches how import behaves in browser environments, assuming a typically configured server. URLs # ES modules are resolved and cached as URLs. This means that special characters must be percent-encoded , such as # with %23 and ? with %3F . file: , node: , and data: URL schemes are supported. A specifier like 'https://example.com/app.js' is not supported natively in Node.js unless using a custom HTTPS loader . file: URLs # Modules are loaded multiple times if the import specifier used to resolve them has a different query or fragment. import './foo.mjs?query=1' ; // loads ./foo.mjs with query of "?query=1" import './foo.mjs?query=2' ; // loads ./foo.mjs with query of "?query=2" copy The volume root may be referenced via / , // , or file:/// . Given the differences between URL and path resolution (such as percent encoding details), it is recommended to use url.pathToFileURL when importing a path. data: imports # Added in: v12.10.0 data: URLs are supported for importing with the following MIME types: * text/javascript for ES modules * application/json for JSON * application/wasm for Wasm import 'data:text/javascript,console.log("hello!");' ; import _ from 'data:application/json,"world!"' with { type : 'json' }; copy data: URLs only resolve bare specifiers for builtin modules and absolute specifiers . Resolving relative specifiers does not work because data: is not a special scheme . For example, attempting to load ./foo from data:text/javascript,import "./foo"; fails to resolve because there is no concept of relative resolution for data: URLs. node: imports # History Version Changes v16.0.0, v14.18.0 Added node: import support to require(...) . v14.13.1, v12.20.0 Added in: v14.13.1, v12.20.0 node: URLs are supported as an alternative means to load Node.js builtin modules. This URL scheme allows for builtin modules to be referenced by valid absolute URL strings. import fs from 'node:fs/promises' ; copy Import attributes # History Version Changes v21.0.0 Switch from Import Assertions to Import Attributes. v17.1.0, v16.14.0 Added in: v17.1.0, v16.14.0 Stability: 1 .1 - Active development This feature was previously named "Import assertions", and using the assert keyword instead of with . Any uses in code of the prior assert keyword should be updated to use with instead. The Import Attributes proposal adds an inline syntax for module import statements to pass on more information alongside the module specifier. import fooData from './foo.json' with { type : 'json' }; const { default : barData } = await import ( './bar.json' , { with : { type : 'json' } }); copy Node.js supports the following type values, for which the attribute is mandatory: Attribute type Needed for 'json' JSON modules Builtin modules # Core modules provide named exports of their public API. A default export is also provided which is the value of the CommonJS exports. The default export can be used for, among other things, modifying the named exports. Named exports of builtin modules are updated only by calling module.syncBuiltinESMExports() . import EventEmitter from 'node:events' ; const e = new EventEmitter (); copy import { readFile } from 'node:fs' ; readFile ( './foo.txt' , ( err, source ) => { if (err) { console . error (err); } else { console . log (source); } }); copy import fs, { readFileSync } from 'node:fs' ; import { syncBuiltinESMExports } from 'node:module' ; import { Buffer } from 'node:buffer' ; fs. readFileSync = () => Buffer . from ( 'Hello, ESM' ); syncBuiltinESMExports (); fs. readFileSync === readFileSync; copy import() expressions # Dynamic import() is supported in both CommonJS and ES modules. In CommonJS modules it can be used to load ES modules. import.meta # * <Object> The import.meta meta property is an Object that contains the following properties. import.meta.dirname # Added in: v21.2.0 Stability: 1 .2 - Release candidate * <string> The directory name of the current module. This is the same as the path.dirname() of the import.meta.filename . Caveat : only present on file: modules. import.meta.filename # Added in: v21.2.0 Stability: 1 .2 - Release candidate * <string> The full absolute path and filename of the current module, with * symlinks resolved. * This is the same as the url.fileURLToPath() of the * import.meta.url . Caveat only local modules support this property. Modules not using the file: protocol will not provide it. import.meta.url # * <string> The absolute file: URL of the module. This is defined exactly the same as it is in browsers providing the URL of the current module file. This enables useful patterns such as relative file loading: import { readFileSync } from 'node:fs' ; const buffer = readFileSync ( new URL ( './data.proto' , import . meta . url )); copy import.meta.resolve(specifier) # History Version Changes v20.6.0 Unflag import.meta.resolve , with parentURL parameter still flagged. v20.6.0 This API no longer throws when targeting file: URLs that do not map to an existing file on the local FS. v20.0.0 This API now returns a string synchronously instead of a Promise. v16.2.0, v14.18.0 Add support for WHATWG URL object to parentURL parameter. v13.9.0, v12.16.2 Added in: v13.9.0, v12.16.2 Stability: 1 .2 - Release candidate * specifier <string> The module specifier to resolve relative to the current module. * Returns: <string> The absolute URL string that the specifier would resolve to. import.meta.resolve is a module-relative resolution function scoped to each module, returning the URL string. const dependencyAsset = import . meta . resolve ( 'component-lib/asset.css' ); // file:///app/node_modules/component-lib/asset.css import . meta . resolve ( './dep.js' ); // file:///app/dep.js copy All features of the Node.js module resolution are supported. Dependency resolutions are subject to the permitted exports resolutions within the package. Caveats : * This can result in synchronous file-system operations, which can impact performance similarly to require.resolve . * This feature is not available within custom loaders (it would create a deadlock). Non-standard API : When using the --experimental-import-meta-resolve flag, that function accepts a second argument: * parent <string> | <URL> An optional absolute parent module URL to resolve from. Default: import.meta.url Interoperability with CommonJS # import statements # An import statement can reference an ES module or a CommonJS module. import statements are permitted only in ES modules, but dynamic import() expressions are supported in CommonJS for loading ES modules. When importing CommonJS modules , the module.exports object is provided as the default export. Named exports may be available, provided by static analysis as a convenience for better ecosystem compatibility. require # The CommonJS module require always treats the files it references as CommonJS. Using require to load an ES module is not supported because ES modules have asynchronous execution. Instead, use import() to load an ES module from a CommonJS module. CommonJS Namespaces # CommonJS modules consist of a module.exports object which can be of any type. When importing a CommonJS module, it can be reliably imported using the ES module default import or its corresponding sugar syntax: import { default as cjs } from 'cjs' ; // The following import statement is "syntax sugar" (equivalent but sweeter) // for `{ default as cjsSugar }` in the above import statement: import cjsSugar from 'cjs' ; console . log (cjs); console . log (cjs === cjsSugar); // Prints: // <module.exports> // true copy The ECMAScript Module Namespace representation of a CommonJS module is always a namespace with a default export key pointing to the CommonJS module.exports value. This Module Namespace Exotic Object can be directly observed either when using import * as m from 'cjs' or a dynamic import: import * as m from 'cjs' ; console . log (m); console . log (m === await import ( 'cjs' )); // Prints: // [Module] { default: <module.exports> } // true copy For better compatibility with existing usage in the JS ecosystem, Node.js in addition attempts to determine the CommonJS named exports of every imported CommonJS module to provide them as separate ES module exports using a static analysis process. For example, consider a CommonJS module written: // cjs.cjs exports . name = 'exported' ; copy The preceding module supports named imports in ES modules: import { name } from './cjs.cjs' ; console . log (name); // Prints: 'exported' import cjs from './cjs.cjs' ; console . log (cjs); // Prints: { name: 'exported' } import * as m from './cjs.cjs' ; console . log (m); // Print

Links found on this page

  1. Node.js [direct]
  2. About this documentation [direct]
  3. Usage and example [direct]
  4. Assertion testing [direct]
  5. Asynchronous context tracking [direct]
  6. Async hooks [direct]
  7. Buffer [direct]
  8. C++ addons [direct]
  9. C/C++ addons with Node-API [direct]
  10. C++ embedder API [direct]
  11. Child processes [direct]
  12. Cluster [direct]
  13. Command-line options [direct]
  14. Console [direct]
  15. Corepack [direct]
  16. Crypto [direct]
  17. Debugger [direct]
  18. Deprecated APIs [direct]
  19. Diagnostics Channel [direct]
  20. DNS [direct]
  21. Domain [direct]
  22. Errors [direct]
  23. Events [direct]
  24. File system [direct]
  25. Globals [direct]
  26. HTTP [direct]
  27. HTTP/2 [direct]
  28. HTTPS [direct]
  29. Inspector [direct]
  30. Internationalization [direct]
  31. Modules: CommonJS modules [direct]
  32. Modules: ECMAScript modules [direct]
  33. Modules: node:module API [direct]
  34. Modules: Packages [direct]
  35. Net [direct]
  36. OS [direct]
  37. Path [direct]
  38. Performance hooks [direct]
  39. Permissions [direct]
  40. Process [direct]
  41. Punycode [direct]
  42. Query strings [direct]
  43. Readline [direct]
  44. REPL [direct]
  45. Report [direct]
  46. Single executable applications [direct]
  47. Stream [direct]
  48. String decoder [direct]
  49. Test runner [direct]
  50. Timers [direct]
  51. TLS/SSL [direct]
  52. Trace events [direct]
  53. TTY [direct]
  54. UDP/datagram [direct]
  55. URL [direct]
  56. Utilities [direct]
  57. V8 [direct]
  58. VM [direct]
  59. WASI [direct]
  60. Web Crypto API [direct]
  61. Web Streams API [direct]
  62. Worker threads [direct]
  63. Zlib [direct]
  64. Code repository and issue tracker [direct]
  65. Index [direct]
  66. 20.x LTS [direct]
  67. 19.x [direct]
  68. 18.x LTS [direct]
  69. 17.x [direct]
  70. 16.x [direct]
  71. 15.x [direct]
  72. 14.x [direct]
  73. 13.x [direct]
  74. 12.x [direct]
  75. 11.x [direct]
  76. 10.x [direct]
  77. 9.x [direct]
  78. 8.x [direct]
  79. View on single page [direct]
  80. View as JSON [direct]