{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.0.json","id":"esm","path":"/esm","type":"misc","module":null,"title":"Modules: ECMAScript modules","introducedIn":"v8.5.0","sourceLink":null,"stability":{"index":"2","description":"Stable"},"added":["v8.5.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v23.1.0","v22.12.0","v20.18.3","v18.20.5"],"prUrl":"https://github.com/nodejs/node/pull/55333","commit":null,"description":"Import attributes are no longer experimental."},{"versions":["v22.0.0"],"prUrl":"https://github.com/nodejs/node/pull/52104","commit":null,"description":"Drop support for import assertions."},{"versions":["v21.0.0","v20.10.0","v18.20.0"],"prUrl":"https://github.com/nodejs/node/pull/50140","commit":null,"description":"Add experimental support for import attributes."},{"versions":["v20.0.0","v18.19.0"],"prUrl":"https://github.com/nodejs/node/pull/44710","commit":null,"description":"Module customization hooks are executed off the main thread."},{"versions":["v18.6.0","v16.17.0"],"prUrl":"https://github.com/nodejs/node/pull/42623","commit":null,"description":"Add support for chaining module customization hooks."},{"versions":["v17.1.0","v16.14.0"],"prUrl":"https://github.com/nodejs/node/pull/40250","commit":null,"description":"Add experimental support for import assertions."},{"versions":["v17.0.0","v16.12.0"],"prUrl":"https://github.com/nodejs/node/pull/37468","commit":null,"description":"Consolidate customization hooks, removed `getFormat`, `getSource`, `transformSource`, and `getGlobalPreloadCode` hooks added `load` and `globalPreload` hooks allowed returning `format` from either `resolve` or `load` hooks."},{"versions":["v15.3.0","v14.17.0","v12.22.0"],"prUrl":"https://github.com/nodejs/node/pull/35781","commit":null,"description":"Stabilize modules implementation."},{"versions":["v14.13.0","v12.20.0"],"prUrl":"https://github.com/nodejs/node/pull/35249","commit":null,"description":"Support for detection of CommonJS named exports."},{"versions":["v14.8.0"],"prUrl":"https://github.com/nodejs/node/pull/34558","commit":null,"description":"Unflag Top-Level Await."},{"versions":["v14.0.0","v13.14.0","v12.20.0"],"prUrl":"https://github.com/nodejs/node/pull/31974","commit":null,"description":"Remove experimental modules warning."},{"versions":["v13.2.0","v12.17.0"],"prUrl":"https://github.com/nodejs/node/pull/29866","commit":null,"description":"Loading ECMAScript modules no longer requires a command-line flag."},{"versions":["v12.0.0"],"prUrl":"https://github.com/nodejs/node/pull/26745","commit":null,"description":"Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field."}],"description":"","summary":"","examples":[],"children":[{"kind":"section","id":"introduction","name":"esm","title":"Introduction","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"ECMAScript modules are [the official standard format](https://tc39.github.io/ecma262/#sec-modules) to package JavaScript\ncode for reuse. Modules are defined using a variety of [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and\n[`export`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) statements.\n\nThe following example of an ES module exports a function:\n\n```js\n// addTwo.mjs\nfunction addTwo(num) {\n  return num + 2;\n}\n\nexport { addTwo };\n```\n\nThe following example of an ES module imports the function from `addTwo.mjs`:\n\n```js\n// app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));\n```\n\nNode.js fully supports ECMAScript modules as they are currently specified and\nprovides interoperability between them and its original module format,\n[CommonJS](modules.html).\n\n<i id=\"esm_package_json_type_field\"></i><i id=\"esm_package_scope_and_file_extensions\"></i><i id=\"esm_input_type_flag\"></i>","summary":"ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of `import` and `export` statements.","examples":[{"language":"js","displayName":null,"code":"// addTwo.mjs\nfunction addTwo(num) {\n  return num + 2;\n}\n\nexport { addTwo };"},{"language":"js","displayName":null,"code":"// app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));"}],"children":[]},{"kind":"section","id":"enabling","name":"Enabling","title":"Enabling","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Node.js has two module systems: [CommonJS](modules.html) modules and ECMAScript modules.\n\nAuthors can tell Node.js to interpret JavaScript as an ES module via the `.mjs`\nfile extension, the `package.json` [`\"type\"`](packages.html#type) field with a value `\"module\"`,\nor the [`--input-type`](cli.html#--input-typetype) flag with a value of `\"module\"`. These are explicit\nmarkers of code being intended to run as an ES module.\n\nInversely, authors can explicitly tell Node.js to interpret JavaScript as\nCommonJS via the `.cjs` file extension, the `package.json` [`\"type\"`](packages.html#type) field\nwith a value `\"commonjs\"`, or the [`--input-type`](cli.html#--input-typetype) flag with a value of\n`\"commonjs\"`.\n\nWhen code lacks explicit markers for either module system, Node.js will inspect\nthe source code of a module to look for ES module syntax. If such syntax is\nfound, Node.js will run the code as an ES module; otherwise it will run the\nmodule as CommonJS. See [Determining module system](packages.html#determining-module-system) for more details.\n\n<i id=\"esm_package_entry_points\"></i><i id=\"esm_main_entry_point_export\"></i><i id=\"esm_subpath_exports\"></i><i id=\"esm_package_exports_fallbacks\"></i><i id=\"esm_exports_sugar\"></i><i id=\"esm_conditional_exports\"></i><i id=\"esm_nested_conditions\"></i><i id=\"esm_self_referencing_a_package_using_its_name\"></i><i id=\"esm_internal_package_imports\"></i><i id=\"esm_dual_commonjs_es_module_packages\"></i><i id=\"esm_dual_package_hazard\"></i><i id=\"esm_writing_dual_packages_while_avoiding_or_minimizing_hazards\"></i><i id=\"esm_approach_1_use_an_es_module_wrapper\"></i><i id=\"esm_approach_2_isolate_state\"></i>","summary":"Node.js has two module systems: CommonJS modules and ECMAScript modules.","examples":[],"children":[]},{"kind":"section","id":"packages","name":"Packages","title":"Packages","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"This section was moved to [Modules: Packages](packages.html).","summary":"This section was moved to Modules: Packages.","examples":[],"children":[]},{"kind":"section","id":"import-specifiers","name":"import Specifiers","title":"`import` Specifiers","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"","summary":"","examples":[],"children":[{"kind":"section","id":"terminology","name":"Terminology","title":"Terminology","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The *specifier* of an `import` statement is the string after the `from` keyword,\ne.g. `'node:path'` in `import { sep } from 'node:path'`. Specifiers are also\nused in `export from` statements, and as the argument to an `import()`\nexpression.\n\nThere are three types of specifiers:\n\n* *Relative specifiers* like `'./startup.js'` or `'../config.mjs'`. They refer\n  to a path relative to the location of the importing file. *The file extension\n  is always necessary for these.*\n\n* *Bare specifiers* like `'some-package'` or `'some-package/shuffle'`. They can\n  refer to the main entry point of a package by the package name, or a\n  specific feature module within a package prefixed by the package name as per\n  the examples respectively. *Including the file extension is only necessary\n  for packages without an [`\"exports\"`](packages.html#exports) field.*\n\n* *Absolute specifiers* like `'file:///opt/nodejs/config.js'`. They refer\n  directly and explicitly to a full path.\n\nBare specifier resolutions are handled by the [Node.js module\nresolution and loading algorithm](#resolution-algorithm-specification).\nAll other specifier resolutions are always only resolved with\nthe standard relative [URL](https://url.spec.whatwg.org/) resolution semantics.\n\nLike in CommonJS, module files within packages can be accessed by appending a\npath to the package name unless the package's [`package.json`](packages.html#nodejs-packagejson-field-definitions) contains an\n[`\"exports\"`](packages.html#exports) field, in which case files within packages can only be accessed\nvia the paths defined in [`\"exports\"`](packages.html#exports).\n\nFor details on these package resolution rules that apply to bare specifiers in\nthe Node.js module resolution, see the [packages documentation](packages.html).","summary":"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.","examples":[],"children":[]},{"kind":"section","id":"mandatory-file-extensions","name":"Mandatory file extensions","title":"Mandatory file extensions","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"A file extension must be provided when using the `import` keyword to resolve\nrelative or absolute specifiers. Directory indexes (e.g. `'./startup/index.js'`)\nmust also be fully specified.\n\nThis behavior matches how `import` behaves in browser environments, assuming a\ntypically configured server.","summary":"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.","examples":[],"children":[]},{"kind":"section","id":"urls","name":"URLs","title":"URLs","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"ES modules are resolved and cached as URLs. This means that special characters\nmust be [percent-encoded](url.html#percent-encoding-in-urls), such as `#` with `%23` and `?` with `%3F`.\n\n`file:`, `node:`, and `data:` URL schemes are supported. A specifier like\n`'https://example.com/app.js'` is not supported natively in Node.js unless using\na [custom HTTPS loader](module.html#import-from-https).","summary":"ES modules are resolved and cached as URLs. This means that special characters must be percent-encoded, such as `#` with `%23` and `?` with `%3F`.","examples":[],"children":[{"kind":"section","id":"file-urls","name":"file: URLs","title":"`file:` URLs","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Modules are loaded multiple times if the `import` specifier used to resolve\nthem has a different query or fragment.\n\n```js\nimport './foo.mjs?query=1'; // loads ./foo.mjs with query of \"?query=1\"\nimport './foo.mjs?query=2'; // loads ./foo.mjs with query of \"?query=2\"\n```\n\nThe volume root may be referenced via `/`, `//`, or `file:///`. Given the\ndifferences between [URL](https://url.spec.whatwg.org/) and path resolution (such as percent encoding\ndetails), it is recommended to use [url.pathToFileURL](url.html#urlpathtofileurlpath-options) when importing a path.","summary":"Modules are loaded multiple times if the `import` specifier used to resolve them has a different query or fragment.","examples":[{"language":"js","displayName":null,"code":"import './foo.mjs?query=1'; // loads ./foo.mjs with query of \"?query=1\"\nimport './foo.mjs?query=2'; // loads ./foo.mjs with query of \"?query=2\""}],"children":[]},{"kind":"section","id":"data-imports","name":"data: imports","title":"`data:` imports","scope":"module","overloadOf":null,"stability":null,"added":["v12.10.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"[`data:` URLs](https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data) are supported for importing with the following MIME types:\n\n* `text/javascript` for ES modules\n* `application/json` for JSON\n* `application/wasm` for Wasm\n\n```js\nimport 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"' with { type: 'json' };\n```\n\n`data:` URLs only resolve [bare specifiers](#terminology) for builtin modules\nand [absolute specifiers](#terminology). Resolving\n[relative specifiers](#terminology) does not work because `data:` is not a\n[special scheme](https://url.spec.whatwg.org/#special-scheme). For example, attempting to load `./foo`\nfrom `data:text/javascript,import \"./foo\";` fails to resolve because there\nis no concept of relative resolution for `data:` URLs.","summary":"`data:` URLs are supported for importing with the following MIME types:","examples":[{"language":"js","displayName":null,"code":"import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"' with { type: 'json' };"}],"children":[]},{"kind":"section","id":"node-imports","name":"node: imports","title":"`node:` imports","scope":"module","overloadOf":null,"stability":null,"added":["v14.13.1","v12.20.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v16.0.0","v14.18.0"],"prUrl":"https://github.com/nodejs/node/pull/37246","commit":null,"description":"Added `node:` import support to `require(...)`."}],"description":"`node:` URLs are supported as an alternative means to load Node.js builtin\nmodules. This URL scheme allows for builtin modules to be referenced by valid\nabsolute URL strings.\n\n```js\nimport fs from 'node:fs/promises';\n```\n\n<a id=\"import-assertions\"></a>","summary":"`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.","examples":[{"language":"js","displayName":null,"code":"import fs from 'node:fs/promises';"}],"children":[]}]}]},{"kind":"section","id":"import-attributes","name":"Import attributes","title":"Import attributes","scope":"module","overloadOf":null,"stability":null,"added":["v17.1.0","v16.14.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v21.0.0","v20.10.0","v18.20.0"],"prUrl":"https://github.com/nodejs/node/pull/50140","commit":null,"description":"Switch from Import Assertions to Import Attributes."}],"description":"[Import attributes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import/with) are an inline syntax for module import\nstatements to pass on more information alongside the module specifier.\n\n```js\nimport fooData from './foo.json' with { type: 'json' };\n\nconst { default: barData } =\n  await import('./bar.json', { with: { type: 'json' } });\n```\n\nNode.js only supports the `type` attribute, for which it supports the following values:\n\n| Attribute `type` | Needed for                    |\n| ---------------- | ----------------------------- |\n| `'json'`         | [JSON modules](#json-modules) |\n| `'text'`         | [Text modules](#text-modules) |\n\nThe `type: 'json'` attribute is mandatory when importing JSON modules.\nThe `type: 'text'` attribute is mandatory when importing text modules.","summary":"Import attributes are an inline syntax for module import statements to pass on more information alongside the module specifier.","examples":[{"language":"js","displayName":null,"code":"import fooData from './foo.json' with { type: 'json' };\n\nconst { default: barData } =\n  await import('./bar.json', { with: { type: 'json' } });"}],"children":[]},{"kind":"section","id":"built-in-modules","name":"Built-in modules","title":"Built-in modules","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"[Built-in modules](modules.html#built-in-modules) provide named exports of their public API. A\ndefault export is also provided which is the value of the CommonJS exports.\nThe default export can be used for, among other things, modifying the named\nexports. Named exports of built-in modules are updated only by calling\n[`module.syncBuiltinESMExports()`](module.html#modulesyncbuiltinesmexports).\n\n```js\nimport EventEmitter from 'node:events';\nconst e = new EventEmitter();\n```\n\n```js\nimport { readFile } from 'node:fs';\nreadFile('./foo.txt', (err, source) => {\n  if (err) {\n    console.error(err);\n  } else {\n    console.log(source);\n  }\n});\n```\n\n```js\nimport fs, { readFileSync } from 'node:fs';\nimport { syncBuiltinESMExports } from 'node:module';\nimport { Buffer } from 'node:buffer';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;\n```\n\n> When importing built-in modules, all the named exports (i.e. properties of the module exports object)\n> are populated even if they are not individually accessed.\n> This can make initial imports of built-in modules slightly slower compared to loading them with\n> `require()` or `process.getBuiltinModule()`, where the module exports object is evaluated immediately,\n> but some of its properties may only be initialized when first accessed individually.","summary":"Built-in 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 built-in modules are updated only by calling `module.syncBuiltinESMExports()`.","examples":[{"language":"js","displayName":null,"code":"import EventEmitter from 'node:events';\nconst e = new EventEmitter();"},{"language":"js","displayName":null,"code":"import { readFile } from 'node:fs';\nreadFile('./foo.txt', (err, source) => {\n  if (err) {\n    console.error(err);\n  } else {\n    console.log(source);\n  }\n});"},{"language":"js","displayName":null,"code":"import fs, { readFileSync } from 'node:fs';\nimport { syncBuiltinESMExports } from 'node:module';\nimport { Buffer } from 'node:buffer';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;"}],"children":[]},{"kind":"section","id":"import-expressions","name":"import() expressions","title":"`import()` expressions","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"[Dynamic `import()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) provides an asynchronous way to import modules. It is\nsupported in both CommonJS and ES modules, and can be used to load both CommonJS\nand ES modules.","summary":"Dynamic `import()` provides an asynchronous way to import modules. It is supported in both CommonJS and ES modules, and can be used to load both CommonJS and ES modules.","examples":[],"children":[]},{"kind":"property","id":"importmeta","name":"meta","title":"`import.meta`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"default":null,"description":"The `import.meta` meta property is an `Object` that contains the following\nproperties. It is only supported in ES modules.","summary":"The `import.meta` meta property is an `Object` that contains the following properties. It is only supported in ES modules.","examples":[],"children":[{"kind":"property","id":"importmetadirname","name":"dirname","title":"`import.meta.dirname`","scope":"module","overloadOf":null,"stability":null,"added":["v21.2.0","v20.11.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.16.0"],"prUrl":"https://github.com/nodejs/node/pull/58011","commit":null,"description":"This property is no longer experimental."}],"type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"default":null,"description":"The directory name of the current module.\n\nThis is the same as the [`path.dirname()`](path.html#pathdirnamepath) of the [`import.meta.filename`](#importmetafilename).\n\n> **Caveat**: only present on `file:` modules.","summary":"This is the same as the `path.dirname()` of the `import.meta.filename`.","examples":[],"children":[]},{"kind":"property","id":"importmetafilename","name":"filename","title":"`import.meta.filename`","scope":"module","overloadOf":null,"stability":null,"added":["v21.2.0","v20.11.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.16.0"],"prUrl":"https://github.com/nodejs/node/pull/58011","commit":null,"description":"This property is no longer experimental."}],"type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"default":null,"description":"The full absolute path and filename of the current module, with\nsymlinks resolved.\n\nThis is the same as the [`url.fileURLToPath()`](url.html#urlfileurltopathurl-options) of the [`import.meta.url`](#importmetaurl).\n\n> **Caveat** only local modules support this property. Modules not using the\n> `file:` protocol will not provide it.","summary":"This is the same as the `url.fileURLToPath()` of the `import.meta.url`.","examples":[],"children":[]},{"kind":"property","id":"importmetaurl","name":"url","title":"`import.meta.url`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"default":null,"description":"The absolute `file:` URL of the module.\n\nThis is defined exactly the same as it is in browsers providing the URL of the\ncurrent module file.\n\nThis enables useful patterns such as relative file loading:\n\n```js\nimport { readFileSync } from 'node:fs';\nconst buffer = readFileSync(new URL('./data.proto', import.meta.url));\n```","summary":"This is defined exactly the same as it is in browsers providing the URL of the current module file.","examples":[{"language":"js","displayName":null,"code":"import { readFileSync } from 'node:fs';\nconst buffer = readFileSync(new URL('./data.proto', import.meta.url));"}],"children":[]},{"kind":"property","id":"importmetamain","name":"main","title":"`import.meta.main`","scope":"module","overloadOf":null,"stability":{"index":"1.0","description":"Early development"},"added":["v24.2.0","v22.18.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"`true` when the current module is the entry point of the current process; `false` otherwise.\n\nEquivalent to `require.main === module` in CommonJS.\n\nAnalogous to Python's `__name__ == \"__main__\"`.\n\n```js\nexport function foo() {\n  return 'Hello, world';\n}\n\nfunction main() {\n  const message = foo();\n  console.log(message);\n}\n\nif (import.meta.main) main();\n// `foo` can be imported from another module without possible side-effects from `main`\n```","summary":"Equivalent to `require.main === module` in CommonJS.","examples":[{"language":"js","displayName":null,"code":"export function foo() {\n  return 'Hello, world';\n}\n\nfunction main() {\n  const message = foo();\n  console.log(message);\n}\n\nif (import.meta.main) main();\n// `foo` can be imported from another module without possible side-effects from `main`"}],"children":[]},{"kind":"method","id":"importmetaresolvespecifier","name":"resolve","title":"`import.meta.resolve(specifier)`","scope":"module","overloadOf":null,"stability":{"index":"1.2","description":"Release candidate"},"added":["v13.9.0","v12.16.2"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v20.6.0","v18.19.0"],"prUrl":"https://github.com/nodejs/node/pull/49028","commit":null,"description":"No longer behind `--experimental-import-meta-resolve` CLI flag, except for the non-standard `parentURL` parameter."},{"versions":["v20.6.0","v18.19.0"],"prUrl":"https://github.com/nodejs/node/pull/49038","commit":null,"description":"This API no longer throws when targeting `file:` URLs that do not map to an existing file on the local FS."},{"versions":["v20.0.0","v18.19.0"],"prUrl":"https://github.com/nodejs/node/pull/44710","commit":null,"description":"This API now returns a string synchronously instead of a Promise."},{"versions":["v16.2.0","v14.18.0"],"prUrl":"https://github.com/nodejs/node/pull/38587","commit":null,"description":"Add support for WHATWG `URL` object to `parentURL` parameter."}],"signature":{"parameters":[{"name":"specifier","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The module specifier to resolve relative to the\ncurrent module.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The absolute URL string that the specifier would resolve to."}},"description":"[`import.meta.resolve`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve) is a module-relative resolution function scoped to\neach module, returning the URL string.\n\n```js\nconst dependencyAsset = import.meta.resolve('component-lib/asset.css');\n// file:///app/node_modules/component-lib/asset.css\nimport.meta.resolve('./dep.js');\n// file:///app/dep.js\n```\n\nAll features of the Node.js module resolution are supported. Dependency\nresolutions are subject to the permitted exports resolutions within the package.\n\n**Caveats**:\n\n* This can result in synchronous file-system operations, which\n  can impact performance similarly to `require.resolve`.\n* This feature is not available within custom loaders (it would\n  create a deadlock).\n\n**Non-standard API**:\n\nWhen using the `--experimental-import-meta-resolve` flag, that function accepts\na second argument:\n\n* `parent` {string | URL} An optional absolute parent module URL to resolve from.\n  **Default:** `import.meta.url`","summary":"`import.meta.resolve` is a module-relative resolution function scoped to each module, returning the URL string.","examples":[{"language":"js","displayName":null,"code":"const dependencyAsset = import.meta.resolve('component-lib/asset.css');\n// file:///app/node_modules/component-lib/asset.css\nimport.meta.resolve('./dep.js');\n// file:///app/dep.js"}],"children":[]}]},{"kind":"section","id":"interoperability-with-commonjs","name":"Interoperability with CommonJS","title":"Interoperability with CommonJS","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"","summary":"","examples":[],"children":[{"kind":"section","id":"import-statements","name":"import statements","title":"`import` statements","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"An `import` statement can reference an ES module or a CommonJS module.\n`import` statements are permitted only in ES modules, but dynamic [`import()`](#import-expressions)\nexpressions are supported in CommonJS for loading ES modules.\n\nWhen importing [CommonJS modules](#commonjs-namespaces), the\n`module.exports` object is provided as the default export. Named exports may be\navailable, provided by static analysis as a convenience for better ecosystem\ncompatibility.","summary":"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.","examples":[],"children":[]},{"kind":"section","id":"require","name":"require","title":"`require`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The CommonJS module `require` currently only supports loading synchronous ES\nmodules (that is, ES modules that do not use top-level `await`).\n\nSee [Loading ECMAScript modules using `require()`](modules.html#loading-ecmascript-modules-using-require) for details.","summary":"The CommonJS module `require` currently only supports loading synchronous ES modules (that is, ES modules that do not use top-level `await`).","examples":[],"children":[]},{"kind":"section","id":"commonjs-namespaces","name":"CommonJS Namespaces","title":"CommonJS Namespaces","scope":"module","overloadOf":null,"stability":null,"added":["v14.13.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v23.0.0"],"prUrl":"https://github.com/nodejs/node/pull/53848","commit":null,"description":"Added `'module.exports'` export marker to CJS namespaces."}],"description":"CommonJS modules consist of a `module.exports` object which can be of any type.\n\nTo support this, when importing CommonJS from an ECMAScript module, a namespace\nwrapper for the CommonJS module is constructed, which always provides a\n`default` export key pointing to the CommonJS `module.exports` value.\n\nIn addition, a heuristic static analysis is performed against the source text of\nthe CommonJS module to get a best-effort static list of exports to provide on\nthe namespace from values on `module.exports`. This is necessary since these\nnamespaces must be constructed prior to the evaluation of the CJS module.\n\nThese CommonJS namespace objects also provide the `default` export as a\n`'module.exports'` named export, in order to unambiguously indicate that their\nrepresentation in CommonJS uses this value, and not the namespace value. This\nmirrors the semantics of the handling of the `'module.exports'` export name in\n[`require(esm)`](modules.html#loading-ecmascript-modules-using-require) interop support.\n\nWhen importing a CommonJS module, it can be reliably imported using the ES\nmodule default import or its corresponding sugar syntax:\n\n```js\nimport { default as cjs } from 'cjs';\n// Identical to the above\nimport cjsSugar from 'cjs';\n\nconsole.log(cjs);\nconsole.log(cjs === cjsSugar);\n// Prints:\n//   <module.exports>\n//   true\n```\n\nThis Module Namespace Exotic Object can be directly observed either when using\n`import * as m from 'cjs'` or a dynamic import:\n\n```js\nimport * as m from 'cjs';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n//   [Module] { default: <module.exports>, 'module.exports': <module.exports> }\n//   true\n```\n\nFor better compatibility with existing usage in the JS ecosystem, Node.js\nin addition attempts to determine the CommonJS named exports of every imported\nCommonJS module to provide them as separate ES module exports using a static\nanalysis process.\n\nFor example, consider a CommonJS module written:\n\n```cjs\n// cjs.cjs\nexports.name = 'exported';\n```\n\nThe preceding module supports named imports in ES modules:\n\n```js\nimport { name } from './cjs.cjs';\nconsole.log(name);\n// Prints: 'exported'\n\nimport cjs from './cjs.cjs';\nconsole.log(cjs);\n// Prints: { name: 'exported' }\n\nimport * as m from './cjs.cjs';\nconsole.log(m);\n// Prints:\n//   [Module] {\n//     default: { name: 'exported' },\n//     'module.exports': { name: 'exported' },\n//     name: 'exported'\n//   }\n```\n\nAs can be seen from the last example of the Module Namespace Exotic Object being\nlogged, the `name` export is copied off of the `module.exports` object and set\ndirectly on the ES module namespace when the module is imported.\n\nLive binding updates or new exports added to `module.exports` are not detected\nfor these named exports.\n\nThe detection of named exports is based on common syntax patterns but does not\nalways correctly detect named exports. In these cases, using the default\nimport form described above can be a better option.\n\nNamed exports detection covers many common export patterns, reexport patterns\nand build tool and transpiler outputs. See [merve](https://github.com/anonrig/merve/tree/v1.0.0) for the exact\nsemantics implemented.","summary":"CommonJS modules consist of a `module.exports` object which can be of any type.","examples":[{"language":"js","displayName":null,"code":"import { default as cjs } from 'cjs';\n// Identical to the above\nimport cjsSugar from 'cjs';\n\nconsole.log(cjs);\nconsole.log(cjs === cjsSugar);\n// Prints:\n//   <module.exports>\n//   true"},{"language":"js","displayName":null,"code":"import * as m from 'cjs';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n//   [Module] { default: <module.exports>, 'module.exports': <module.exports> }\n//   true"},{"language":"cjs","displayName":null,"code":"// cjs.cjs\nexports.name = 'exported';"},{"language":"js","displayName":null,"code":"import { name } from './cjs.cjs';\nconsole.log(name);\n// Prints: 'exported'\n\nimport cjs from './cjs.cjs';\nconsole.log(cjs);\n// Prints: { name: 'exported' }\n\nimport * as m from './cjs.cjs';\nconsole.log(m);\n// Prints:\n//   [Module] {\n//     default: { name: 'exported' },\n//     'module.exports': { name: 'exported' },\n//     name: 'exported'\n//   }"}],"children":[]},{"kind":"section","id":"differences-between-es-modules-and-commonjs","name":"Differences between ES modules and CommonJS","title":"Differences between ES modules and CommonJS","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"","summary":"","examples":[],"children":[{"kind":"section","id":"no-require-exports-or-moduleexports","name":"No require, exports, or module.exports","title":"No `require`, `exports`, or `module.exports`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"In most cases, the ES module `import` can be used to load CommonJS modules.\n\nIf needed, a `require` function can be constructed within an ES module using\n[`module.createRequire()`](module.html#modulecreaterequirefilename).","summary":"In most cases, the ES module `import` can be used to load CommonJS modules.","examples":[],"children":[]},{"kind":"section","id":"no-__filename-or-__dirname","name":"No __filename or __dirname","title":"No `__filename` or `__dirname`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"These CommonJS variables are not available in ES modules.\n\n`__filename` and `__dirname` use cases can be replicated via\n[`import.meta.filename`](#importmetafilename) and [`import.meta.dirname`](#importmetadirname).","summary":"These CommonJS variables are not available in ES modules.","examples":[],"children":[]},{"kind":"section","id":"no-addon-loading","name":"No Addon Loading","title":"No Addon Loading","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"[Addons](addons.html) are not currently supported with ES module imports.\n\nThey can instead be loaded with [`module.createRequire()`](module.html#modulecreaterequirefilename) or\n[`process.dlopen`](process.html#processdlopenmodule-filename-flags).","summary":"Addons are not currently supported with ES module imports.","examples":[],"children":[]},{"kind":"section","id":"no-requiremain","name":"No require.main","title":"No `require.main`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"To replace `require.main === module`, there is the [`import.meta.main`](#importmetamain) API.","summary":"To replace `require.main === module`, there is the `import.meta.main` API.","examples":[],"children":[]},{"kind":"section","id":"no-requireresolve","name":"No require.resolve","title":"No `require.resolve`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Relative resolution can be handled via `new URL('./local', import.meta.url)`.\n\nFor a complete `require.resolve` replacement, there is the\n[import.meta.resolve](#importmetaresolvespecifier) API.\n\nAlternatively `module.createRequire()` can be used.","summary":"Relative resolution can be handled via `new URL('./local', import.meta.url)`.","examples":[],"children":[]},{"kind":"section","id":"no-node_path","name":"No NODE_PATH","title":"No `NODE_PATH`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"`NODE_PATH` is not part of resolving `import` specifiers. Please use symlinks\nif this behavior is desired.","summary":"`NODE_PATH` is not part of resolving `import` specifiers. Please use symlinks if this behavior is desired.","examples":[],"children":[]},{"kind":"section","id":"no-requireextensions","name":"No require.extensions","title":"No `require.extensions`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"`require.extensions` is not used by `import`. Module customization hooks can\nprovide a replacement.","summary":"`require.extensions` is not used by `import`. Module customization hooks can provide a replacement.","examples":[],"children":[]},{"kind":"section","id":"no-requirecache","name":"No require.cache","title":"No `require.cache`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"`require.cache` is not used by `import` as the ES module loader has its own\nseparate cache.\n\n<i id=\"esm_experimental_json_modules\"></i>","summary":"`require.cache` is not used by `import` as the ES module loader has its own separate cache.","examples":[],"children":[]}]}]},{"kind":"section","id":"json-modules","name":"JSON modules","title":"JSON modules","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v23.1.0","v22.12.0","v20.18.3","v18.20.5"],"prUrl":"https://github.com/nodejs/node/pull/55333","commit":null,"description":"JSON modules are no longer experimental."}],"description":"JSON files can be referenced by `import`:\n\n```js\nimport packageConfig from './package.json' with { type: 'json' };\n```\n\nThe `with { type: 'json' }` syntax is mandatory; see [Import Attributes](#import-attributes).\n\nThe imported JSON only exposes a `default` export. There is no support for named\nexports. A cache entry is created in the CommonJS cache to avoid duplication.\nThe same object is returned in CommonJS if the JSON module has already been\nimported from the same path.","summary":"JSON files can be referenced by `import`:","examples":[{"language":"js","displayName":null,"code":"import packageConfig from './package.json' with { type: 'json' };"}],"children":[]},{"kind":"section","id":"text-modules","name":"Text modules","title":"Text modules","scope":"module","overloadOf":null,"stability":{"index":"1.0","description":"Early development"},"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Text modules are available behind the `--experimental-import-text` flag.\n\nText files can be referenced by `import`:\n\n```js\nimport message from './message.txt' with { type: 'text' };\n```\n\nThe `with { type: 'text' }` syntax is mandatory; see [Import Attributes](#import-attributes).\n\nThe imported text only exposes a `default` export whose value is the module\nsource as a string.\n\n<i id=\"esm_experimental_wasm_modules\"></i>","summary":"Text modules are available behind the `--experimental-import-text` flag.","examples":[{"language":"js","displayName":null,"code":"import message from './message.txt' with { type: 'text' };"}],"children":[]},{"kind":"section","id":"wasm-modules","name":"Wasm modules","title":"Wasm modules","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.5.0","v22.19.0"],"prUrl":"https://github.com/nodejs/node/pull/57038","commit":null,"description":"Wasm modules no longer require the `--experimental-wasm-modules` flag."}],"description":"Importing both WebAssembly module instances and WebAssembly source phase\nimports is supported.\n\nBoth of these integrations are in line with the\n[ES Module Integration Proposal for WebAssembly](https://github.com/webassembly/esm-integration).","summary":"Importing both WebAssembly module instances and WebAssembly source phase imports is supported.","examples":[],"children":[{"kind":"section","id":"wasm-source-phase-imports","name":"Wasm Source Phase Imports","title":"Wasm Source Phase Imports","scope":"module","overloadOf":null,"stability":{"index":"1.2","description":"Release candidate"},"added":["v24.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The [Source Phase Imports](https://github.com/tc39/proposal-source-phase-imports) proposal allows the `import source` keyword\ncombination to import a `WebAssembly.Module` object directly, instead of getting\na module instance already instantiated with its dependencies.\n\nThis is useful when needing custom instantiations for Wasm, while still\nresolving and loading it through the ES module integration.\n\nFor example, to create multiple instances of a module, or to pass custom imports\ninto a new instance of `library.wasm`:\n\n```js\nimport source libraryModule from './library.wasm';\n\nconst instance1 = await WebAssembly.instantiate(libraryModule, importObject1);\n\nconst instance2 = await WebAssembly.instantiate(libraryModule, importObject2);\n```\n\nIn addition to the static source phase, there is also a dynamic variant of the\nsource phase via the `import.source` dynamic phase import syntax:\n\n```js\nconst dynamicLibrary = await import.source('./library.wasm');\n\nconst instance = await WebAssembly.instantiate(dynamicLibrary, importObject);\n```","summary":"The Source Phase Imports proposal allows the `import source` keyword combination to import a `WebAssembly.Module` object directly, instead of getting a module instance already instantiated with its dependencies.","examples":[{"language":"js","displayName":null,"code":"import source libraryModule from './library.wasm';\n\nconst instance1 = await WebAssembly.instantiate(libraryModule, importObject1);\n\nconst instance2 = await WebAssembly.instantiate(libraryModule, importObject2);"},{"language":"js","displayName":null,"code":"const dynamicLibrary = await import.source('./library.wasm');\n\nconst instance = await WebAssembly.instantiate(dynamicLibrary, importObject);"}],"children":[]},{"kind":"section","id":"javascript-string-builtins","name":"JavaScript String Builtins","title":"JavaScript String Builtins","scope":"module","overloadOf":null,"stability":{"index":"1.2","description":"Release candidate"},"added":["v24.5.0","v22.19.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"When importing WebAssembly modules, the\n[WebAssembly JS String Builtins Proposal](https://github.com/WebAssembly/js-string-builtins) is automatically enabled through the\nESM Integration. This allows WebAssembly modules to directly use efficient\ncompile-time string builtins from the `wasm:js-string` namespace.\n\nFor example, the following Wasm module exports a string `getLength` function using\nthe `wasm:js-string` `length` builtin:\n\n```text\n(module\n  ;; Compile-time import of the string length builtin.\n  (import \"wasm:js-string\" \"length\" (func $string_length (param externref) (result i32)))\n\n  ;; Define getLength, taking a JS value parameter assumed to be a string,\n  ;; calling string length on it and returning the result.\n  (func $getLength (param $str externref) (result i32)\n    local.get $str\n    call $string_length\n  )\n\n  ;; Export the getLength function.\n  (export \"getLength\" (func $get_length))\n)\n```\n\n```js\nimport { getLength } from './string-len.wasm';\ngetLength('foo'); // Returns 3.\n```\n\nWasm builtins are compile-time imports that are linked during module compilation\nrather than during instantiation. They do not behave like normal module graph\nimports and they cannot be inspected via `WebAssembly.Module.imports(mod)`\nor virtualized unless recompiling the module using the direct\n`WebAssembly.compile` API with string builtins disabled.\n\nString constants may also be imported from the `wasm:js/string-constants` builtin\nimport URL, allowing static JS string globals to be defined:\n\n```text\n(module\n  (import \"wasm:js/string-constants\" \"hello\" (global $hello externref))\n)\n```\n\nImporting a module in the source phase before it has been instantiated will also\nuse the compile-time builtins automatically:\n\n```js\nimport source mod from './string-len.wasm';\nconst { exports: { getLength } } = await WebAssembly.instantiate(mod, {});\ngetLength('foo'); // Also returns 3.\n```","summary":"When importing WebAssembly modules, the WebAssembly JS String Builtins Proposal is automatically enabled through the ESM Integration. This allows WebAssembly modules to directly use efficient compile-time string builtins from the `wasm:js-string` namespace.","examples":[{"language":"text","displayName":null,"code":"(module\n  ;; Compile-time import of the string length builtin.\n  (import \"wasm:js-string\" \"length\" (func $string_length (param externref) (result i32)))\n\n  ;; Define getLength, taking a JS value parameter assumed to be a string,\n  ;; calling string length on it and returning the result.\n  (func $getLength (param $str externref) (result i32)\n    local.get $str\n    call $string_length\n  )\n\n  ;; Export the getLength function.\n  (export \"getLength\" (func $get_length))\n)"},{"language":"js","displayName":null,"code":"import { getLength } from './string-len.wasm';\ngetLength('foo'); // Returns 3."},{"language":"text","displayName":null,"code":"(module\n  (import \"wasm:js/string-constants\" \"hello\" (global $hello externref))\n)"},{"language":"js","displayName":null,"code":"import source mod from './string-len.wasm';\nconst { exports: { getLength } } = await WebAssembly.instantiate(mod, {});\ngetLength('foo'); // Also returns 3."}],"children":[]},{"kind":"section","id":"wasm-instance-phase-imports","name":"Wasm Instance Phase Imports","title":"Wasm Instance Phase Imports","scope":"module","overloadOf":null,"stability":{"index":"1.1","description":"Active development"},"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Instance imports allow any `.wasm` files to be imported as normal modules,\nsupporting their module imports in turn.\n\nFor example, an `index.js` containing:\n\n```js\nimport * as M from './library.wasm';\nconsole.log(M);\n```\n\nexecuted under:\n\n```bash\nnode index.mjs\n```\n\nwould provide the exports interface for the instantiation of `library.wasm`.","summary":"Instance imports allow any `.wasm` files to be imported as normal modules, supporting their module imports in turn.","examples":[{"language":"js","displayName":null,"code":"import * as M from './library.wasm';\nconsole.log(M);"},{"language":"bash","displayName":null,"code":"node index.mjs"}],"children":[]},{"kind":"section","id":"reserved-wasm-namespaces","name":"Reserved Wasm Namespaces","title":"Reserved Wasm Namespaces","scope":"module","overloadOf":null,"stability":null,"added":["v24.5.0","v22.19.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"When importing WebAssembly module instances, they cannot use import module\nnames or import/export names that start with reserved prefixes:\n\n* `wasm-js:` - reserved in all module import names, module names and export\n  names.\n* `wasm:` - reserved in module import names and export names (imported module\n  names are allowed in order to support future builtin polyfills).\n\nImporting a module using the above reserved names will throw a\n`WebAssembly.LinkError`.\n\n<i id=\"esm_experimental_top_level_await\"></i>","summary":"When importing WebAssembly module instances, they cannot use import module names or import/export names that start with reserved prefixes:","examples":[],"children":[]}]},{"kind":"section","id":"top-level-await","name":"Top-level await","title":"Top-level `await`","scope":"module","overloadOf":null,"stability":null,"added":["v14.8.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `await` keyword may be used in the top level body of an ECMAScript module.\n\nAssuming an `a.mjs` with\n\n```js\nexport const five = await Promise.resolve(5);\n```\n\nAnd a `b.mjs` with\n\n```js\nimport { five } from './a.mjs';\n\nconsole.log(five); // Logs `5`\n```\n\n```bash\nnode b.mjs # works\n```\n\nIf a top level `await` expression never resolves, the `node` process will exit\nwith a `13` [status code](process.html#exit-codes).\n\n```js\nimport { spawn } from 'node:child_process';\nimport { execPath } from 'node:process';\n\nspawn(execPath, [\n  '--input-type=module',\n  '--eval',\n  // Never-resolving Promise:\n  'await new Promise(() => {})',\n]).once('exit', (code) => {\n  console.log(code); // Logs `13`\n});\n```\n\n<i id=\"esm_experimental_loaders\"></i>","summary":"The `await` keyword may be used in the top level body of an ECMAScript module.","examples":[{"language":"js","displayName":null,"code":"export const five = await Promise.resolve(5);"},{"language":"js","displayName":null,"code":"import { five } from './a.mjs';\n\nconsole.log(five); // Logs `5`"},{"language":"bash","displayName":null,"code":"node b.mjs # works"},{"language":"js","displayName":null,"code":"import { spawn } from 'node:child_process';\nimport { execPath } from 'node:process';\n\nspawn(execPath, [\n  '--input-type=module',\n  '--eval',\n  // Never-resolving Promise:\n  'await new Promise(() => {})',\n]).once('exit', (code) => {\n  console.log(code); // Logs `13`\n});"}],"children":[]},{"kind":"section","id":"loaders","name":"Loaders","title":"Loaders","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The former Loaders documentation is now at\n[Modules: Customization hooks](module.html#customization-hooks).","summary":"The former Loaders documentation is now at Modules: Customization hooks.","examples":[],"children":[]},{"kind":"section","id":"resolution-and-loading-algorithm","name":"Resolution and loading algorithm","title":"Resolution and loading algorithm","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"","summary":"","examples":[],"children":[{"kind":"section","id":"features","name":"Features","title":"Features","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The default resolver has the following properties:\n\n* FileURL-based resolution as is used by ES modules\n* Relative and absolute URL resolution\n* No default extensions\n* No folder mains\n* Bare specifier package resolution lookup through node\\_modules\n* Does not fail on unknown extensions or protocols\n* Can optionally provide a hint of the format to the loading phase\n\nThe default loader has the following properties\n\n* Support for builtin module loading via `node:` URLs\n* Support for \"inline\" module loading via `data:` URLs\n* Support for `file:` module loading\n* Fails on any other URL protocol\n* Fails on unknown extensions for `file:` loading\n  (supports only `.cjs`, `.js`, and `.mjs`)\n\nWhen the [`--experimental-package-map`](cli.html#--experimental-package-mappath) flag is enabled, bare specifier\nresolution first consults the package map configuration. If the importing\nmodule is within a mapped package and the specifier matches a declared\ndependency, the package map resolution takes precedence. See [Package maps](packages.html#package-maps)\nfor details.","summary":"The default resolver has the following properties:","examples":[],"children":[]},{"kind":"section","id":"resolution-algorithm","name":"Resolution algorithm","title":"Resolution algorithm","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The algorithm to load an ES module specifier is given through the\n**ESM\\_RESOLVE** method below. It returns the resolved URL for a\nmodule specifier relative to a parentURL.\n\nThe resolution algorithm determines the full resolved URL for a module\nload, along with its suggested module format. The resolution algorithm\ndoes not determine whether the resolved URL protocol can be loaded,\nor whether the file extensions are permitted, instead these validations\nare applied by Node.js during the load phase\n(for example, if it was asked to load a URL that has a protocol that is\nnot `file:`, `data:` or `node:`.\n\nThe algorithm also tries to determine the format of the file based\non the extension (see `ESM_FILE_FORMAT` algorithm below). If it does\nnot recognize the file extension (eg if it is not `.mjs`, `.cjs`, or\n`.json`), then a format of `undefined` is returned,\nwhich will throw during the load phase.\n\nThe algorithm to determine the module format of a resolved URL is\nprovided by **ESM\\_FILE\\_FORMAT**, which returns the unique module\nformat for any file. The *\"module\"* format is returned for an ECMAScript\nModule, while the *\"commonjs\"* format is used to indicate loading through the\nlegacy CommonJS loader. Additional formats such as *\"addon\"* can be extended in\nfuture updates.\n\nIn the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.\n\n*defaultConditions* is the conditional environment name array,\n`[\"node\", \"import\"]`.\n\nThe resolver can throw the following errors:\n\n* *Invalid Module Specifier*: Module specifier is an invalid URL, package name\n  or package subpath specifier.\n* *Invalid Package Configuration*: package.json configuration is invalid or\n  contains an invalid configuration.\n* *Invalid Package Target*: Package exports or imports define a target module\n  for the package that is an invalid type or string target.\n* *Package Path Not Exported*: Package exports do not define or permit a target\n  subpath in the package for the given module.\n* *Package Import Not Defined*: Package imports do not define the specifier.\n* *Module Not Found*: The package or module requested does not exist.\n* *Unsupported Directory Import*: The resolved path corresponds to a directory,\n  which is not a supported target for module imports.","summary":"The algorithm to load an ES module specifier is given through the **ESM_RESOLVE** method below. It returns the resolved URL for a module specifier relative to a parentURL.","examples":[],"children":[]},{"kind":"section","id":"resolution-algorithm-specification","name":"Resolution Algorithm Specification","title":"Resolution Algorithm Specification","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"**ESM\\_RESOLVE**(*specifier*, *parentURL*)\n\n> 1. Let *resolved* be **undefined**.\n> 2. If *specifier* is a valid URL, then\n>    1. Set *resolved* to the result of parsing and reserializing\n>       *specifier* as a URL.\n> 3. Otherwise, if *specifier* starts with *\"/\"*, *\"./\"*, or *\"../\"*, then\n>    1. Set *resolved* to the URL resolution of *specifier* relative to\n>       *parentURL*.\n> 4. Otherwise, if *specifier* starts with *\"#\"*, then\n>    1. Set *resolved* to the result of\n>       **PACKAGE\\_IMPORTS\\_RESOLVE**(*specifier*,\n>       *parentURL*, *defaultConditions*).\n> 5. Otherwise,\n>    1. Note: *specifier* is now a bare specifier.\n>    2. Set *resolved* the result of\n>       **PACKAGE\\_RESOLVE**(*specifier*, *parentURL*).\n> 6. Let *format* be **undefined**.\n> 7. If *resolved* is a *\"file:\"* URL, then\n>    1. If *resolved* contains any percent encodings of *\"/\"* or *\"\\\\\"* (*\"%2F\"*\n>       and *\"%5C\"* respectively), then\n>       1. Throw an *Invalid Module Specifier* error.\n>    2. If the file at *resolved* is a directory, then\n>       1. Throw an *Unsupported Directory Import* error.\n>    3. If the file at *resolved* does not exist, then\n>       1. Throw a *Module Not Found* error.\n>    4. Set *resolved* to the real path of *resolved*, maintaining the\n>       same URL querystring and fragment components.\n>    5. Set *format* to the result of **ESM\\_FILE\\_FORMAT**(*resolved*).\n> 8. Otherwise,\n>    1. Set *format* the module format of the content type associated with the\n>       URL *resolved*.\n> 9. Return *format* and *resolved* to the loading phase\n\n**PACKAGE\\_RESOLVE**(*packageSpecifier*, *parentURL*)\n\n> 1. Let *packageName* be **undefined**.\n> 2. If *packageSpecifier* is an empty string, then\n>    1. Throw an *Invalid Module Specifier* error.\n> 3. If *packageSpecifier* is a Node.js builtin module name, then\n>    1. Return the string *\"node:\"* concatenated with *packageSpecifier*.\n> 4. If *packageSpecifier* does not start with *\"@\"*, then\n>    1. Set *packageName* to the substring of *packageSpecifier* until the first\n>       *\"/\"* separator or the end of the string.\n> 5. Otherwise,\n>    1. If *packageSpecifier* does not contain a *\"/\"* separator, then\n>       1. Throw an *Invalid Module Specifier* error.\n>    2. Set *packageName* to the substring of *packageSpecifier*\n>       until the second *\"/\"* separator or the end of the string.\n> 6. If *packageName* starts with *\".\"* or contains *\"\\\\\"* or *\"%\"*, then\n>    1. Throw an *Invalid Module Specifier* error.\n> 7. Let *packageSubpath* be *\".\"* concatenated with the substring of\n>    *packageSpecifier* from the position at the length of *packageName*.\n> 8. Let *selfUrl* be the result of\n>    **PACKAGE\\_SELF\\_RESOLVE**(*packageName*, *packageSubpath*, *parentURL*).\n> 9. If *selfUrl* is not **undefined**, return *selfUrl*.\n> 10. While *parentURL* is not the file system root,\n>     1. Let *packageURL* be the URL resolution of *\"node\\_modules/\"*\n>        concatenated with *packageName*, relative to *parentURL*.\n>     2. Set *parentURL* to the parent folder URL of *parentURL*.\n>     3. If the folder at *packageURL* does not exist, then\n>        1. Continue the next loop iteration.\n>     4. Let *pjson* be the result of **READ\\_PACKAGE\\_JSON**(*packageURL*).\n>     5. If *pjson* is not **null** and *pjson*.*exports* is not **null** or\n>        **undefined**, then\n>        1. Return the result of **PACKAGE\\_EXPORTS\\_RESOLVE**(*packageURL*,\n>           *packageSubpath*, *pjson.exports*, *defaultConditions*).\n>     6. Otherwise, if *packageSubpath* is equal to *\".\"*, then\n>        1. If *pjson.main* is a string, then\n>           1. Return the URL resolution of *main* in *packageURL*.\n>     7. Otherwise,\n>        1. Return the URL resolution of *packageSubpath* in *packageURL*.\n> 11. Throw a *Module Not Found* error.\n\n**PACKAGE\\_SELF\\_RESOLVE**(*packageName*, *packageSubpath*, *parentURL*)\n\n> 1. Let *packageURL* be the result of **LOOKUP\\_PACKAGE\\_SCOPE**(*parentURL*).\n> 2. If *packageURL* is **null**, then\n>    1. Return **undefined**.\n> 3. Let *pjson* be the result of **READ\\_PACKAGE\\_JSON**(*packageURL*).\n> 4. If *pjson* is **null** or if *pjson*.*exports* is **null** or\n>    **undefined**, then\n>    1. Return **undefined**.\n> 5. If *pjson.name* is equal to *packageName*, then\n>    1. Return the result of **PACKAGE\\_EXPORTS\\_RESOLVE**(*packageURL*,\n>       *packageSubpath*, *pjson.exports*, *defaultConditions*).\n> 6. Otherwise, return **undefined**.\n\n**PACKAGE\\_EXPORTS\\_RESOLVE**(*packageURL*, *subpath*, *exports*, *conditions*)\n\nNote: This function is directly invoked by the CommonJS resolution algorithm.\n\n> 1. If *exports* is an Object with both a key starting with *\".\"* and a key not\n>    starting with *\".\"*, throw an *Invalid Package Configuration* error.\n> 2. If *subpath* is equal to *\".\"*, then\n>    1. Let *mainExport* be **undefined**.\n>    2. If *exports* is a String or Array, or an Object containing no keys\n>       starting with *\".\"*, then\n>       1. Set *mainExport* to *exports*.\n>    3. Otherwise if *exports* is an Object containing a *\".\"* property, then\n>       1. Set *mainExport* to *exports*\\[*\".\"*].\n>    4. If *mainExport* is not **undefined**, then\n>       1. Let *resolved* be the result of **PACKAGE\\_TARGET\\_RESOLVE**(\n>          *packageURL*, *mainExport*, **null**, **false**, *conditions*).\n>       2. If *resolved* is not **null** or **undefined**, return *resolved*.\n> 3. Otherwise, if *exports* is an Object and all keys of *exports* start with\n>    *\".\"*, then\n>    1. Assert: *subpath* begins with *\"./\"*.\n>    2. Let *resolved* be the result of **PACKAGE\\_IMPORTS\\_EXPORTS\\_RESOLVE**(\n>       *subpath*, *exports*, *packageURL*, **false**, *conditions*).\n>    3. If *resolved* is not **null** or **undefined**, return *resolved*.\n> 4. Throw a *Package Path Not Exported* error.\n\n**PACKAGE\\_IMPORTS\\_RESOLVE**(*specifier*, *parentURL*, *conditions*)\n\nNote: This function is directly invoked by the CommonJS resolution algorithm.\n\n> 1. Assert: *specifier* begins with *\"#\"*.\n> 2. If *specifier* is exactly equal to *\"#\"*, then\n>    1. Throw an *Invalid Module Specifier* error.\n> 3. Let *packageURL* be the result of **LOOKUP\\_PACKAGE\\_SCOPE**(*parentURL*).\n> 4. If *packageURL* is not **null**, then\n>    1. Let *pjson* be the result of **READ\\_PACKAGE\\_JSON**(*packageURL*).\n>    2. If *pjson.imports* is a non-null Object, then\n>       1. Let *resolved* be the result of\n>          **PACKAGE\\_IMPORTS\\_EXPORTS\\_RESOLVE**(\n>          *specifier*, *pjson.imports*, *packageURL*, **true**, *conditions*).\n>       2. If *resolved* is not **null** or **undefined**, return *resolved*.\n> 5. Throw a *Package Import Not Defined* error.\n\n**PACKAGE\\_IMPORTS\\_EXPORTS\\_RESOLVE**(*matchKey*, *matchObj*, *packageURL*,\n*isImports*, *conditions*)\n\n> 1. If *matchKey* ends in *\"/\"*, then\n>    1. Throw an *Invalid Module Specifier* error.\n> 2. If *matchKey* is a key of *matchObj* and does not contain *\"\\*\"*, then\n>    1. Let *target* be the value of *matchObj*\\[*matchKey*].\n>    2. Return the result of **PACKAGE\\_TARGET\\_RESOLVE**(*packageURL*,\n>       *target*, **null**, *isImports*, *conditions*).\n> 3. Let *expansionKeys* be the list of keys of *matchObj* containing only a\n>    single *\"\\*\"*, sorted by the sorting function **PATTERN\\_KEY\\_COMPARE**\n>    which orders in descending order of specificity.\n> 4. For each key *expansionKey* in *expansionKeys*, do\n>    1. Let *patternBase* be the substring of *expansionKey* up to but excluding\n>       the first *\"\\*\"* character.\n>    2. If *matchKey* starts with but is not equal to *patternBase*, then\n>       1. Let *patternTrailer* be the substring of *expansionKey* from the\n>          index after the first *\"\\*\"* character.\n>       2. If *patternTrailer* has zero length, or if *matchKey* ends with\n>          *patternTrailer* and the length of *matchKey* is greater than or\n>          equal to the length of *expansionKey*, then\n>          1. Let *target* be the value of *matchObj*\\[*expansionKey*].\n>          2. Let *patternMatch* be the substring of *matchKey* starting at the\n>             index of the length of *patternBase* up to the length of\n>             *matchKey* minus the length of *patternTrailer*.\n>          3. Return the result of **PACKAGE\\_TARGET\\_RESOLVE**(*packageURL*,\n>             *target*, *patternMatch*, *isImports*, *conditions*).\n> 5. Return **null**.\n\n**PATTERN\\_KEY\\_COMPARE**(*keyA*, *keyB*)\n\n> 1. Assert: *keyA* contains only a single *\"\\*\"*.\n> 2. Assert: *keyB* contains only a single *\"\\*\"*.\n> 3. Let *baseLengthA* be the index of *\"\\*\"* in *keyA*.\n> 4. Let *baseLengthB* be the index of *\"\\*\"* in *keyB*.\n> 5. If *baseLengthA* is greater than *baseLengthB*, return -1.\n> 6. If *baseLengthB* is greater than *baseLengthA*, return 1.\n> 7. If the length of *keyA* is greater than the length of *keyB*, return -1.\n> 8. If the length of *keyB* is greater than the length of *keyA*, return 1.\n> 9. Return 0.\n\n**PACKAGE\\_TARGET\\_RESOLVE**(*packageURL*, *target*, *patternMatch*,\n*isImports*, *conditions*)\n\n> 1. If *target* is a String, then\n>    1. If *target* does not start with *\"./\"*, then\n>       1. If *isImports* is **false**, or if *target* starts with *\"../\"* or\n>          *\"/\"*, or if *target* is a valid URL, then\n>          1. Throw an *Invalid Package Target* error.\n>       2. If *patternMatch* is a String, then\n>          1. Return **PACKAGE\\_RESOLVE**(*target* with every instance of *\"\\*\"*\n>             replaced by *patternMatch*, *packageURL* + *\"/\"*).\n>       3. Return **PACKAGE\\_RESOLVE**(*target*, *packageURL* + *\"/\"*).\n>    2. If *target* split on *\"/\"* or *\"\\\\\"* contains any *\"\"*, *\".\"*, *\"..\"*,\n>       or *\"node\\_modules\"* segments after the first *\".\"* segment, case\n>       insensitive and including percent encoded variants, throw an *Invalid\n>       Package Target* error.\n>    3. Let *resolvedTarget* be the URL resolution of the concatenation of\n>       *packageURL* and *target*.\n>    4. Assert: *packageURL* is contained in *resolvedTarget*.\n>    5. If *patternMatch* is **null**, then\n>       1. Return *resolvedTarget*.\n>    6. If *patternMatch* split on *\"/\"* or *\"\\\\\"* contains any *\"\"*, *\".\"*,\n>       *\"..\"*, or *\"node\\_modules\"* segments, case insensitive and including\n>       percent encoded variants, throw an *Invalid Module Specifier* error.\n>    7. Return the URL resolution of *resolvedTarget* with every instance of\n>       *\"\\*\"* replaced with *patternMatch*.\n> 2. Otherwise, if *target* is a non-null Object, then\n>    1. If *target* contains any index property keys, as defined in ECMA-262\n>       [6.1.7 Array Index](https://tc39.es/ecma262/#integer-index), throw an *Invalid Package Configuration* error.\n>    2. For each property *p* of *target*, in object insertion order as,\n>       1. If *p* equals *\"default\"* or *conditions* contains an entry for *p*,\n>          then\n>          1. Let *targetValue* be the value of the *p* property in *target*.\n>          2. Let *resolved* be the result of **PACKAGE\\_TARGET\\_RESOLVE**(\n>             *packageURL*, *targetValue*, *patternMatch*, *isImports*,\n>             *conditions*).\n>          3. If *resolved* is equal to **undefined**, continue the loop.\n>          4. Return *resolved*.\n>    3. Return **undefined**.\n> 3. Otherwise, if *target* is an Array, then\n>    1. If \\_target.length is zero, return **null**.\n>    2. For each item *targetValue* in *target*, do\n>       1. Let *resolved* be the result of **PACKAGE\\_TARGET\\_RESOLVE**(\n>          *packageURL*, *targetValue*, *patternMatch*, *isImports*,\n>          *conditions*), continuing the loop on any *Invalid Package Target*\n>          error.\n>       2. If *resolved* is **undefined**, continue the loop.\n>       3. Return *resolved*.\n>    3. Return or throw the last fallback resolution **null** return or error.\n> 4. Otherwise, if *target* is *null*, return **null**.\n> 5. Otherwise throw an *Invalid Package Target* error.\n\n**ESM\\_FILE\\_FORMAT**(*url*)\n\n> 1. Assert: *url* corresponds to an existing file.\n> 2. If *url* ends in *\".mjs\"*, then\n>    1. Return *\"module\"*.\n> 3. If *url* ends in *\".cjs\"*, then\n>    1. Return *\"commonjs\"*.\n> 4. If *url* ends in *\".json\"*, then\n>    1. Return *\"json\"*.\n> 5. If *url* ends in\n>    *\".wasm\"*, then\n>    1. Return *\"wasm\"*.\n> 6. If `--experimental-addon-modules` is enabled and *url* ends in\n>    *\".node\"*, then\n>    1. Return *\"addon\"*.\n> 7. Let *packageURL* be the result of **LOOKUP\\_PACKAGE\\_SCOPE**(*url*).\n> 8. Let *pjson* be the result of **READ\\_PACKAGE\\_JSON**(*packageURL*).\n> 9. Let *packageType* be **null**.\n> 10. If *pjson?.type* is *\"module\"* or *\"commonjs\"*, then\n>     1. Set *packageType* to *pjson.type*.\n> 11. If *url* ends in *\".js\"*, then\n>     1. If *packageType* is not **null**, then\n>        1. Return *packageType*.\n>     2. If the result of **DETECT\\_MODULE\\_SYNTAX**(*source*) is true, then\n>        1. Return *\"module\"*.\n>     3. Return *\"commonjs\"*.\n> 12. If *url* does not have any extension, then\n>     1. If *packageType* is *\"module\"* and the file at *url* contains the\n>        \"application/wasm\" content type header for a WebAssembly module, then\n>        1. Return *\"wasm\"*.\n>     2. If *packageType* is not **null**, then\n>        1. Return *packageType*.\n>     3. If the result of **DETECT\\_MODULE\\_SYNTAX**(*source*) is true, then\n>        1. Return *\"module\"*.\n>     4. Return *\"commonjs\"*.\n> 13. Return **undefined** (will throw during load phase).\n\n**LOOKUP\\_PACKAGE\\_SCOPE**(*url*)\n\n> 1. Let *scopeURL* be *url*.\n> 2. While *scopeURL* is not the file system root,\n>    1. Set *scopeURL* to the parent URL of *scopeURL*.\n>    2. If *scopeURL* ends in a *\"node\\_modules\"* path segment, return **null**.\n>    3. Let *pjsonURL* be the resolution of *\"package.json\"* within\n>       *scopeURL*.\n>    4. if the file at *pjsonURL* exists, then\n>       1. Return *scopeURL*.\n> 3. Return **null**.\n\n**READ\\_PACKAGE\\_JSON**(*packageURL*)\n\n> 1. Let *pjsonURL* be the resolution of *\"package.json\"* within *packageURL*.\n> 2. If the file at *pjsonURL* does not exist, then\n>    1. Return **null**.\n> 3. If the file at *packageURL* does not parse as valid JSON, then\n>    1. Throw an *Invalid Package Configuration* error.\n> 4. Return the parsed JSON source of the file at *pjsonURL*.\n\n**DETECT\\_MODULE\\_SYNTAX**(*source*)\n\n> 1. Parse *source* as an ECMAScript module.\n> 2. If the parse is successful, then\n>    1. If *source* contains top-level `await`, static `import` or `export`\n>       statements, or `import.meta`, return **true**.\n>    2. If *source* contains a top-level lexical declaration (`const`, `let`,\n>       or `class`) of any of the CommonJS wrapper variables (`require`,\n>       `exports`, `module`, `__filename`, or `__dirname`) then return **true**.\n> 3. Return **false**.","summary":"**ESM_RESOLVE**(_specifier_, _parentURL_)","examples":[],"children":[]},{"kind":"section","id":"customizing-esm-specifier-resolution-algorithm","name":"Customizing ESM specifier resolution algorithm","title":"Customizing ESM specifier resolution algorithm","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"[Module customization hooks](module.html#customization-hooks) provide a mechanism for customizing the ESM\nspecifier resolution algorithm. An example that provides CommonJS-style\nresolution for ESM specifiers is [commonjs-extension-resolution-loader](https://github.com/nodejs/loaders-test/tree/main/commonjs-extension-resolution-loader).","summary":"Module customization hooks provide a mechanism for customizing the ESM specifier resolution algorithm. An example that provides CommonJS-style resolution for ESM specifiers is commonjs-extension-resolution-loader.","examples":[],"children":[]}]}]}