{ "type": "module", "source": "doc/api/esm.md", "introduced_in": "v8.5.0", "stability": 1, "stabilityText": "Experimental", "properties": [ { "textRaw": "`meta` {Object}", "type": "Object", "name": "meta", "desc": "
The import.meta
metaproperty is an Object
that contains the following\nproperty:
url
<string> The absolute file:
URL of the module.ECMAScript modules are the official standard format to package JavaScript\ncode for reuse. Modules are defined using a variety of import
and\nexport
statements.
The following example of an ES module exports a function:
\n// addTwo.mjs\nfunction addTwo(num) {\n return num + 2;\n}\n\nexport { addTwo };\n
\nThe following example of an ES module imports the function from addTwo.mjs
:
// app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));\n
\nNode.js fully supports ECMAScript modules as they are currently specified and\nprovides limited interoperability between them and the existing module format,\nCommonJS.
\nNode.js contains support for ES Modules based upon the\nNode.js EP for ES Modules and the ECMAScript-modules implementation.
\nExpect major changes in the implementation including interoperability support,\nspecifier resolution, and default behavior.
\n\n\n\n
", "type": "misc", "displayName": "esm" }, { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "Node.js treats JavaScript code as CommonJS modules by default.\nAuthors can tell Node.js to treat JavaScript code as ECMAScript modules\nvia the .mjs
file extension, the package.json
\"type\"
field, or the\n--input-type
flag. See\nModules: Packages for more\ndetails.
\n\n\n\n\n\n\n\n\n\n\n\n\n
" }, { "textRaw": "Packages", "name": "packages", "desc": "This section was moved to Modules: Packages.
", "type": "misc", "displayName": "Packages" }, { "textRaw": "`import` Specifiers", "name": "`import`_specifiers", "modules": [ { "textRaw": "Terminology", "name": "terminology", "desc": "The specifier of an import
statement is the string after the from
keyword,\ne.g. 'path'
in import { sep } from 'path'
. Specifiers are also used in\nexport from
statements, and as the argument to an import()
expression.
There are four types of specifiers:
\nBare specifiers like 'some-package'
. They refer to an entry point of a\npackage by the package name.
Deep import specifiers like 'some-package/lib/shuffle.mjs'
. They refer to\na path within a package prefixed by the package name.
Relative specifiers like './startup.js'
or '../config.mjs'
. They refer\nto a path relative to the location of the importing file.
Absolute specifiers like 'file:///opt/nodejs/config.js'
. They refer\ndirectly and explicitly to a full path.
Bare specifiers, and the bare specifier portion of deep import specifiers, are\nstrings; but everything else in a specifier is a URL.
\nOnly file:
and data:
URLs are supported. A specifier like\n'https://example.com/app.js'
may be supported by browsers but it is not\nsupported in Node.js.
Specifiers may not begin with /
or //
. These are reserved for potential\nfuture use. The root of the current volume may be referenced via file:///
.
data:
URLs are supported for importing with the following MIME types:
text/javascript
for ES Modulesapplication/json
for JSONapplication/wasm
for WASM.data:
URLs only resolve Bare specifiers for builtin modules\nand Absolute specifiers. Resolving\nRelative specifiers will not work because data:
is not a\nspecial scheme. For example, attempting to load ./foo
\nfrom data:text/javascript,import \"./foo\";
will fail to resolve since there\nis no concept of relative resolution for data:
URLs. An example of a data:
\nURLs being used is:
import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"';\n
",
"type": "module",
"displayName": "`data:` Imports"
}
],
"type": "module",
"displayName": "Terminology"
}
],
"type": "misc",
"displayName": "`import` Specifiers"
},
{
"textRaw": "Differences between ES modules and CommonJS",
"name": "differences_between_es_modules_and_commonjs",
"modules": [
{
"textRaw": "Mandatory file extensions",
"name": "mandatory_file_extensions",
"desc": "A file extension must be provided when using the import
keyword. Directory\nindexes (e.g. './startup/index.js'
) must also be fully specified.
This behavior matches how import
behaves in browser environments, assuming a\ntypically configured server.
NODE_PATH
is not part of resolving import
specifiers. Please use symlinks\nif this behavior is desired.
These CommonJS variables are not available in ES modules.
\nrequire
can be imported into an ES module using module.createRequire()
.
Equivalents of __filename
and __dirname
can be created inside of each file\nvia import.meta.url
.
import { fileURLToPath } from 'url';\nimport { dirname } from 'path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n
",
"type": "module",
"displayName": "No `require`, `exports`, `module.exports`, `__filename`, `__dirname`"
},
{
"textRaw": "No `require.resolve`",
"name": "no_`require.resolve`",
"desc": "Former use cases relying on require.resolve
to determine the resolved path\nof a module can be supported via import.meta.resolve
, which is experimental\nand supported via the --experimental-import-meta-resolve
flag:
(async () => {\n const dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n})();\n
\nimport.meta.resolve
also accepts a second argument which is the parent module\nfrom which to resolve from:
(async () => {\n // Equivalent to import.meta.resolve('./dep')\n await import.meta.resolve('./dep', import.meta.url);\n})();\n
\nThis function is asynchronous since the ES module resolver in Node.js is\nasynchronous. With the introduction of Top-Level Await, these use cases\nwill be easier as they won't require an async function wrapper.
", "type": "module", "displayName": "No `require.resolve`" }, { "textRaw": "No `require.extensions`", "name": "no_`require.extensions`", "desc": "require.extensions
is not used by import
. The expectation is that loader\nhooks can provide this workflow in the future.
require.cache
is not used by import
. It has a separate cache.
ES modules are resolved and cached based upon\nURL semantics. This means that files containing\nspecial characters such as #
and ?
need to be escaped.
Modules will be loaded multiple times if the import
specifier used to resolve\nthem have a different query or fragment.
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\"\n
\nFor now, only modules using the file:
protocol can be loaded.
require
always treats the files it references as CommonJS. This applies\nwhether require
is used the traditional way within a CommonJS environment, or\nin an ES module environment using module.createRequire()
.
To include an ES module into CommonJS, use import()
.
An import
statement can reference an ES module or a CommonJS module. Other\nfile types such as JSON or native modules are not supported. For those, use\nmodule.createRequire()
.
import
statements are permitted only in ES modules. For similar functionality\nin CommonJS, see import()
.
The specifier of an import
statement (the string after the from
keyword)\ncan either be an URL-style relative path like './file.mjs'
or a package name\nlike 'fs'
.
Like in CommonJS, files within packages can be accessed by appending a path to\nthe package name; unless the package’s package.json
contains an \"exports\"
\nfield, in which case files within packages need to be accessed via the path\ndefined in \"exports\"
.
import { sin, cos } from 'geometry/trigonometry-functions.mjs';\n
\nOnly the “default export” is supported for CommonJS files or packages:
\n\nimport packageMain from 'commonjs-package'; // Works\n\nimport { method } from 'commonjs-package'; // Errors\n
\nIt is also possible to\nimport an ES or CommonJS module for its side effects only.
", "type": "module", "displayName": "`import` statements" }, { "textRaw": "`import()` expressions", "name": "`import()`_expressions", "desc": "Dynamic import()
is supported in both CommonJS and ES modules. It can be\nused to include ES module files from CommonJS code.
CommonJS, JSON, and native modules can be used with\nmodule.createRequire()
.
// cjs.cjs\nmodule.exports = 'cjs';\n\n// esm.mjs\nimport { createRequire } from 'module';\n\nconst require = createRequire(import.meta.url);\n\nconst cjs = require('./cjs.cjs');\ncjs === 'cjs'; // true\n
",
"type": "misc",
"displayName": "CommonJS, JSON, and native modules"
},
{
"textRaw": "Builtin modules",
"name": "builtin_modules",
"desc": "Core modules will 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 builtin modules are updated only by calling\nmodule.syncBuiltinESMExports()
.
import EventEmitter from 'events';\nconst e = new EventEmitter();\n
\nimport { readFile } from 'fs';\nreadFile('./foo.txt', (err, source) => {\n if (err) {\n console.error(err);\n } else {\n console.log(source);\n }\n});\n
\nimport fs, { readFileSync } from 'fs';\nimport { syncBuiltinESMExports } from 'module';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;\n
",
"type": "misc",
"displayName": "Builtin modules"
},
{
"textRaw": "Experimental JSON modules",
"name": "experimental_json_modules",
"desc": "Currently importing JSON modules are only supported in the commonjs
mode\nand are loaded using the CJS loader. WHATWG JSON modules specification are\nstill being standardized, and are experimentally supported by including the\nadditional flag --experimental-json-modules
when running Node.js.
When the --experimental-json-modules
flag is included both the\ncommonjs
and module
mode will use the new experimental JSON\nloader. The imported JSON only exposes a default
, there is no\nsupport for named exports. A cache entry is created in the CommonJS\ncache, to avoid duplication. The same object will be returned in\nCommonJS if the JSON module has already been imported from the\nsame path.
Assuming an index.mjs
with
import packageConfig from './package.json';\n
\nThe --experimental-json-modules
flag is needed for the module\nto work.
node index.mjs # fails\nnode --experimental-json-modules index.mjs # works\n
",
"type": "misc",
"displayName": "Experimental JSON modules"
},
{
"textRaw": "Experimental Wasm modules",
"name": "experimental_wasm_modules",
"desc": "Importing Web Assembly modules is supported under the\n--experimental-wasm-modules
flag, allowing any .wasm
files to be\nimported as normal modules while also supporting their module imports.
This integration is in line with the\nES Module Integration Proposal for Web Assembly.
\nFor example, an index.mjs
containing:
import * as M from './module.wasm';\nconsole.log(M);\n
\nexecuted under:
\nnode --experimental-wasm-modules index.mjs\n
\nwould provide the exports interface for the instantiation of module.wasm
.
The await
keyword may be used in the top level (outside of async functions)\nwithin modules as per the ECMAScript Top-Level await
proposal.
Assuming an a.mjs
with
export const five = await Promise.resolve(5);\n
\nAnd a b.mjs
with
import { five } from './a.mjs';\n\nconsole.log(five); // Logs `5`\n
\nnode b.mjs # works\n
",
"type": "misc",
"displayName": "Experimental top-level `await`"
},
{
"textRaw": "Experimental loaders",
"name": "Experimental loaders",
"type": "misc",
"desc": "Note: This API is currently being redesigned and will still change.
\nTo customize the default module resolution, loader hooks can optionally be\nprovided via a --experimental-loader ./loader-name.mjs
argument to Node.js.
When hooks are used they only apply to ES module loading and not to any\nCommonJS modules loaded.
", "miscs": [ { "textRaw": "Hooks", "name": "hooks", "methods": [ { "textRaw": "`resolve(specifier, context, defaultResolve)`", "type": "method", "name": "resolve", "signatures": [ { "params": [] } ], "desc": "\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
specifier
<string>context
<Object>
conditions
<string[]>parentURL
<string>defaultResolve
<Function>Returns: <Object>
\nurl
<string>The resolve
hook returns the resolved file URL for a given module specifier\nand parent URL. The module specifier is the string in an import
statement or\nimport()
expression, and the parent URL is the URL of the module that imported\nthis one, or undefined
if this is the main entry point for the application.
The conditions
property on the context
is an array of conditions for\nConditional exports that apply to this resolution request. They can be used\nfor looking up conditional mappings elsewhere or to modify the list when calling\nthe default resolution logic.
The current package exports conditions will always be in\nthe context.conditions
array passed into the hook. To guarantee default\nNode.js module specifier resolution behavior when calling defaultResolve
, the\ncontext.conditions
array passed to it must include all elements of the\ncontext.conditions
array originally passed into the resolve
hook.
/**\n * @param {string} specifier\n * @param {{\n * conditions: !Array<string>,\n * parentURL: !(string | undefined),\n * }} context\n * @param {Function} defaultResolve\n * @returns {Promise<{ url: string }>}\n */\nexport async function resolve(specifier, context, defaultResolve) {\n const { parentURL = null } = context;\n if (Math.random() > 0.5) { // Some condition.\n // For some or all specifiers, do some custom logic for resolving.\n // Always return an object of the form {url: <string>}.\n return {\n url: parentURL ?\n new URL(specifier, parentURL).href :\n new URL(specifier).href,\n };\n }\n if (Math.random() < 0.5) { // Another condition.\n // When calling `defaultResolve`, the arguments can be modified. In this\n // case it's adding another value for matching conditional exports.\n return defaultResolve(specifier, {\n ...context,\n conditions: [...context.conditions, 'another-condition'],\n });\n }\n // Defer to Node.js for all other specifiers.\n return defaultResolve(specifier, context, defaultResolve);\n}\n
"
},
{
"textRaw": "`getFormat(url, context, defaultGetFormat)`",
"type": "method",
"name": "getFormat",
"signatures": [
{
"params": []
}
],
"desc": "\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
url
<string>context
<Object>defaultGetFormat
<Function>Returns: <Object>
\nformat
<string>The getFormat
hook provides a way to define a custom method of determining how\na URL should be interpreted. The format
returned also affects what the\nacceptable forms of source values are for a module when parsing. This can be one\nof the following:
format | \nDescription | \nAcceptable Types For source Returned by getSource or transformSource | \n
---|---|---|
'builtin' | \nLoad a Node.js builtin module | \nNot applicable | \n
'commonjs' | \nLoad a Node.js CommonJS module | \nNot applicable | \n
'json' | \nLoad a JSON file | \n{ string , ArrayBuffer , TypedArray } | \n
'module' | \nLoad an ES module | \n{ string , ArrayBuffer , TypedArray } | \n
'wasm' | \nLoad a WebAssembly module | \n{ ArrayBuffer , TypedArray } | \n
Note: These types all correspond to classes defined in ECMAScript.
\nArrayBuffer
object is a SharedArrayBuffer
.TypedArray
object is a Uint8Array
.Note: If the source value of a text-based format (i.e., 'json'
, 'module'
) is\nnot a string, it will be converted to a string using util.TextDecoder
.
/**\n * @param {string} url\n * @param {Object} context (currently empty)\n * @param {Function} defaultGetFormat\n * @returns {Promise<{ format: string }>}\n */\nexport async function getFormat(url, context, defaultGetFormat) {\n if (Math.random() > 0.5) { // Some condition.\n // For some or all URLs, do some custom logic for determining format.\n // Always return an object of the form {format: <string>}, where the\n // format is one of the strings in the preceding table.\n return {\n format: 'module',\n };\n }\n // Defer to Node.js for all other URLs.\n return defaultGetFormat(url, context, defaultGetFormat);\n}\n
"
},
{
"textRaw": "`getSource(url, context, defaultGetSource)`",
"type": "method",
"name": "getSource",
"signatures": [
{
"params": []
}
],
"desc": "\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
url
<string>context
<Object>
format
<string>defaultGetSource
<Function>Returns: <Object>
\nsource
<string> | <SharedArrayBuffer> | <Uint8Array>The getSource
hook provides a way to define a custom method for retrieving\nthe source code of an ES module specifier. This would allow a loader to\npotentially avoid reading files from disk.
/**\n * @param {string} url\n * @param {{ format: string }} context\n * @param {Function} defaultGetSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function getSource(url, context, defaultGetSource) {\n const { format } = context;\n if (Math.random() > 0.5) { // Some condition.\n // For some or all URLs, do some custom logic for retrieving the source.\n // Always return an object of the form {source: <string|buffer>}.\n return {\n source: '...',\n };\n }\n // Defer to Node.js for all other URLs.\n return defaultGetSource(url, context, defaultGetSource);\n}\n
"
},
{
"textRaw": "`transformSource(source, context, defaultTransformSource)`",
"type": "method",
"name": "transformSource",
"signatures": [
{
"params": []
}
],
"desc": "\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
source
<string> | <SharedArrayBuffer> | <Uint8Array>context
<Object>
Returns: <Object>
\nsource
<string> | <SharedArrayBuffer> | <Uint8Array>The transformSource
hook provides a way to modify the source code of a loaded\nES module file after the source string has been loaded but before Node.js has\ndone anything with it.
If this hook is used to convert unknown-to-Node.js file types into executable\nJavaScript, a resolve hook is also necessary in order to register any\nunknown-to-Node.js file extensions. See the transpiler loader example below.
\n/**\n * @param {!(string | SharedArrayBuffer | Uint8Array)} source\n * @param {{\n * format: string,\n * url: string,\n * }} context\n * @param {Function} defaultTransformSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function transformSource(source, context, defaultTransformSource) {\n const { url, format } = context;\n if (Math.random() > 0.5) { // Some condition.\n // For some or all URLs, do some custom logic for modifying the source.\n // Always return an object of the form {source: <string|buffer>}.\n return {\n source: '...',\n };\n }\n // Defer to Node.js for all other sources.\n return defaultTransformSource(source, context, defaultTransformSource);\n}\n
"
},
{
"textRaw": "`getGlobalPreloadCode()`",
"type": "method",
"name": "getGlobalPreloadCode",
"signatures": [
{
"params": []
}
],
"desc": "\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
Sometimes it can be necessary to run some code inside of the same global scope\nthat the application will run in. This hook allows to return a string that will\nbe ran as sloppy-mode script on startup.
\nSimilar to how CommonJS wrappers work, the code runs in an implicit function\nscope. The only argument is a require
-like function that can be used to load\nbuiltins like \"fs\": getBuiltin(request: string)
.
If the code needs more advanced require
features, it will have to construct\nits own require
using module.createRequire()
.
/**\n * @returns {string} Code to run before application startup\n */\nexport function getGlobalPreloadCode() {\n return `\\\nglobalThis.someInjectedProperty = 42;\nconsole.log('I just set some globals!');\n\nconst { createRequire } = getBuiltin('module');\n\nconst require = createRequire(process.cwd() + '/<preload>');\n// [...]\n`;\n}\n
\nThe various loader hooks can be used together to accomplish wide-ranging\ncustomizations of Node.js’ code loading and evaluation behaviors.
" } ], "modules": [ { "textRaw": "HTTPS loader", "name": "https_loader", "desc": "In current Node.js, specifiers starting with https://
are unsupported. The\nloader below registers hooks to enable rudimentary support for such specifiers.\nWhile this may seem like a significant improvement to Node.js core\nfunctionality, there are substantial downsides to actually using this loader:\nperformance is much slower than loading files from disk, there is no caching,\nand there is no security.
// https-loader.mjs\nimport { get } from 'https';\n\nexport function resolve(specifier, context, defaultResolve) {\n const { parentURL = null } = context;\n\n // Normally Node.js would error on specifiers starting with 'https://', so\n // this hook intercepts them and converts them into absolute URLs to be\n // passed along to the later hooks below.\n if (specifier.startsWith('https://')) {\n return {\n url: specifier\n };\n } else if (parentURL && parentURL.startsWith('https://')) {\n return {\n url: new URL(specifier, parentURL).href\n };\n }\n\n // Let Node.js handle all other specifiers.\n return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n // This loader assumes all network-provided JavaScript is ES module code.\n if (url.startsWith('https://')) {\n return {\n format: 'module'\n };\n }\n\n // Let Node.js handle all other URLs.\n return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function getSource(url, context, defaultGetSource) {\n // For JavaScript to be loaded over the network, we need to fetch and\n // return it.\n if (url.startsWith('https://')) {\n return new Promise((resolve, reject) => {\n get(url, (res) => {\n let data = '';\n res.on('data', (chunk) => data += chunk);\n res.on('end', () => resolve({ source: data }));\n }).on('error', (err) => reject(err));\n });\n }\n\n // Let Node.js handle all other URLs.\n return defaultGetSource(url, context, defaultGetSource);\n}\n
\n// main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n
\nWith this loader, running:
\nnode --experimental-loader ./https-loader.mjs ./main.mjs\n
\nWill print the current version of CoffeeScript per the module at the URL in\nmain.mjs
.
Sources that are in formats Node.js doesn’t understand can be converted into\nJavaScript using the transformSource
hook. Before that hook gets called,\nhowever, other hooks need to tell Node.js not to throw an error on unknown file\ntypes; and to tell Node.js how to load this new file type.
This is less performant than transpiling source files before running\nNode.js; a transpiler loader should only be used for development and testing\npurposes.
\n// coffeescript-loader.mjs\nimport { URL, pathToFileURL } from 'url';\nimport CoffeeScript from 'coffeescript';\n\nconst baseURL = pathToFileURL(`${process.cwd()}/`).href;\n\n// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.\nconst extensionsRegex = /\\.coffee$|\\.litcoffee$|\\.coffee\\.md$/;\n\nexport function resolve(specifier, context, defaultResolve) {\n const { parentURL = baseURL } = context;\n\n // Node.js normally errors on unknown file extensions, so return a URL for\n // specifiers ending in the CoffeeScript file extensions.\n if (extensionsRegex.test(specifier)) {\n return {\n url: new URL(specifier, parentURL).href\n };\n }\n\n // Let Node.js handle all other specifiers.\n return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n // Now that we patched resolve to let CoffeeScript URLs through, we need to\n // tell Node.js what format such URLs should be interpreted as. For the\n // purposes of this loader, all CoffeeScript URLs are ES modules.\n if (extensionsRegex.test(url)) {\n return {\n format: 'module'\n };\n }\n\n // Let Node.js handle all other URLs.\n return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function transformSource(source, context, defaultTransformSource) {\n const { url, format } = context;\n\n if (extensionsRegex.test(url)) {\n return {\n source: CoffeeScript.compile(source, { bare: true })\n };\n }\n\n // Let Node.js handle all other sources.\n return defaultTransformSource(source, context, defaultTransformSource);\n}\n
\n# main.coffee\nimport { scream } from './scream.coffee'\nconsole.log scream 'hello, world'\n\nimport { version } from 'process'\nconsole.log \"Brought to you by Node.js version #{version}\"\n
\n# scream.coffee\nexport scream = (str) -> str.toUpperCase()\n
\nWith this loader, running:
\nnode --experimental-loader ./coffeescript-loader.mjs main.coffee\n
\nWill cause main.coffee
to be turned into JavaScript after its source code is\nloaded from disk but before Node.js executes it; and so on for any .coffee
,\n.litcoffee
or .coffee.md
files referenced via import
statements of any\nloaded file.
The resolver has the following properties:
\nThe algorithm to load an ES module specifier is given through the\nESM_RESOLVE method below. It returns the resolved URL for a\nmodule specifier relative to a parentURL.
\nThe algorithm to determine the module format of a resolved URL is\nprovided by ESM_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.
\nIn the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.
\ndefaultConditions is the conditional environment name array,\n[\"node\", \"import\"]
.
The resolver can throw the following errors:
\nESM_RESOLVE(specifier, parentURL)
\n\n\n\n
\n- Let resolved be undefined.
\n- \n
\nIf specifier is a valid URL, then
\n\n
\n- Set resolved to the result of parsing and reserializing\nspecifier as a URL.
\n- \n
\nOtherwise, if specifier starts with \"/\", \"./\" or \"../\", then
\n\n
\n- Set resolved to the URL resolution of specifier relative to\nparentURL.
\n- \n
\nOtherwise, if specifier starts with \"#\", then
\n\n
\n- Set resolved to the destructured value of the result of\nPACKAGE_IMPORTS_RESOLVE(specifier, parentURL,\ndefaultConditions).
\n- \n
\nOtherwise,
\n\n
\n- Note: specifier is now a bare specifier.
\n- Set resolved the result of\nPACKAGE_RESOLVE(specifier, parentURL).
\n- \n
\nIf resolved contains any percent encodings of \"/\" or \"\\\" (\"%2f\"\nand \"%5C\" respectively), then
\n\n
\n- Throw an Invalid Module Specifier error.
\n- \n
\nIf the file at resolved is a directory, then
\n\n
\n- Throw an Unsupported Directory Import error.
\n- \n
\nIf the file at resolved does not exist, then
\n\n
\n- Throw a Module Not Found error.
\n- Set resolved to the real path of resolved.
\n- Let format be the result of ESM_FORMAT(resolved).
\n- Load resolved as module format, format.
\n- Return resolved.
\n
PACKAGE_RESOLVE(packageSpecifier, parentURL)
\n\n\n\n
\n- Let packageName be undefined.
\n- \n
\nIf packageSpecifier is an empty string, then
\n\n
\n- Throw an Invalid Module Specifier error.
\n- \n
\nIf packageSpecifier does not start with \"@\", then
\n\n
\n- Set packageName to the substring of packageSpecifier until the first\n\"/\" separator or the end of the string.
\n- \n
\nOtherwise,
\n\n
\n- \n
\nIf packageSpecifier does not contain a \"/\" separator, then
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Set packageName to the substring of packageSpecifier\nuntil the second \"/\" separator or the end of the string.
\n- \n
\nIf packageName starts with \".\" or contains \"\\\" or \"%\", then
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Let packageSubpath be \".\" concatenated with the substring of\npackageSpecifier from the position at the length of packageName.
\n- Let selfUrl be the result of\nPACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
\n- If selfUrl is not undefined, return selfUrl.
\n- \n
\nIf packageSubpath is \".\" and packageName is a Node.js builtin\nmodule, then
\n\n
\n- Return the string \"nodejs:\" concatenated with packageSpecifier.
\n- \n
\nWhile parentURL is not the file system root,
\n\n
\n- Let packageURL be the URL resolution of \"node_modules/\"\nconcatenated with packageSpecifier, relative to parentURL.
\n- Set parentURL to the parent folder URL of parentURL.
\n- \n
\nIf the folder at packageURL does not exist, then
\n\n
\n- Set parentURL to the parent URL path of parentURL.
\n- Continue the next loop iteration.
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- \n
\nIf pjson is not null and pjson.exports is not null or\nundefined, then
\n\n
\n- Let exports be pjson.exports.
\n- Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath,\npjson.exports, defaultConditions).
\n- \n
\nOtherwise, if packageSubpath is equal to \".\", then
\n\n
\n- Return the result applying the legacy LOAD_AS_DIRECTORY\nCommonJS resolver to packageURL, throwing a Module Not Found\nerror for no resolution.
\n- \n
\nOtherwise,
\n\n
\n- Return the URL resolution of packageSubpath in packageURL.
\n- Throw a Module Not Found error.
\n
PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)
\n\n\n\n
\n- Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
\n- \n
\nIf packageURL is null, then
\n\n
\n- Return undefined.
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- \n
\nIf pjson is null or if pjson.exports is null or\nundefined, then
\n\n
\n- Return undefined.
\n- \n
\nIf pjson.name is equal to packageName, then
\n\n
\n- Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, subpath, pjson.exports,\ndefaultConditions).
\n- Otherwise, return undefined.
\n
PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)
\n\n\n\n
\n- If exports is an Object with both a key starting with \".\" and a key not\nstarting with \".\", throw an Invalid Package Configuration error.
\n- \n
\nIf subpath is equal to \".\", then
\n\n
\n- Let mainExport be undefined.
\n- \n
\nIf exports is a String or Array, or an Object containing no keys\nstarting with \".\", then
\n\n
\n- Set mainExport to exports.
\n- \n
\nOtherwise if exports is an Object containing a \".\" property, then
\n\n
\n- Set mainExport to exports[\".\"].
\n- \n
\nIf mainExport is not undefined, then
\n\n
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, \"\", false, conditions).
\n- \n
\nIf resolved is not null or undefined, then
\n\n
\n- Return resolved.
\n- \n
\nOtherwise, if exports is an Object and all keys of exports start with\n\".\", then
\n\n
\n- Let matchKey be the string \"./\" concatenated with subpath.
\n- Let resolvedMatch be result of PACKAGE_IMPORTS_EXPORTS_RESOLVE(\nmatchKey, exports, packageURL, false, conditions).
\n- \n
\nIf resolvedMatch.resolve is not null or undefined, then
\n\n
\n- Return resolvedMatch.
\n- Throw a Package Path Not Exported error.
\n
PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)
\n\n\n\n
\n- Assert: specifier begins with \"#\".
\n- \n
\nIf specifier is exactly equal to \"#\" or starts with \"#/\", then
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
\n- \n
\nIf packageURL is not null, then
\n\n
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- \n
\nIf pjson.imports is a non-null Object, then
\n\n
\n- Let resolvedMatch be the result of\nPACKAGE_IMPORTS_EXPORTS_RESOLVE(specifier, pjson.imports,\npackageURL, true, conditions).
\n- \n
\nIf resolvedMatch.resolve is not null or undefined, then
\n\n
\n- Return resolvedMatch.
\n- Throw a Package Import Not Defined error.
\n
PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL,\nisImports, conditions)
\n\n\n\n
\n- \n
\nIf matchKey is a key of matchObj, and does not end in \"*\", then
\n\n
\n- Let target be the value of matchObj[matchKey].
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, \"\", isImports, conditions).
\n- Return the object { resolved, exact: true }.
\n- Let expansionKeys be the list of keys of matchObj ending in \"/\",\nsorted by length descending.
\n- \n
\nFor each key expansionKey in expansionKeys, do
\n\n
\n- \n
\nIf matchKey starts with expansionKey, then
\n\n
\n- Let target be the value of matchObj[expansionKey].
\n- Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey.
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, isImports, conditions).
\n- Return the object { resolved, exact: false }.
\n- Return the object { resolved: null, exact: true }.
\n
PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, internal,\nconditions)
\n\n\n\n
\n- \n
\nIf target is a String, then
\n\n
\n- If subpath has non-zero length and target does not end with \"/\",\nthrow an Invalid Module Specifier error.
\n- \n
\nIf target does not start with \"./\", then
\n\n
\n- \n
\nIf internal is true and target does not start with \"../\" or\n\"/\" and is not a valid URL, then
\n\n
\n- Return PACKAGE_RESOLVE(target + subpath,\npackageURL + \"/\")_.
\n- Otherwise, throw an Invalid Package Target error.
\n- If target split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments after the first segment, throw an\nInvalid Module Specifier error.
\n- Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
\n- Assert: resolvedTarget is contained in packageURL.
\n- If subpath split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments, throw an Invalid Module Specifier error.
\n- Return the URL resolution of the concatenation of subpath and\nresolvedTarget.
\n- \n
\nOtherwise, if target is a non-null Object, then
\n\n
\n- If exports contains any index property keys, as defined in ECMA-262\n6.1.7 Array Index, throw an Invalid Package Configuration error.
\n- \n
\nFor each property p of target, in object insertion order as,
\n\n
\n- \n
\nIf p equals \"default\" or conditions contains an entry for p,\nthen
\n\n
\n- Let targetValue be the value of the p property in target.
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, internal, conditions).
\n- If resolved is equal to undefined, continue the loop.
\n- Return resolved.
\n- Return undefined.
\n- \n
\nOtherwise, if target is an Array, then
\n\n
\n- If _target.length is zero, return null.
\n- \n
\nFor each item targetValue in target, do
\n\n
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, internal, conditions),\ncontinuing the loop on any Invalid Package Target error.
\n- If resolved is undefined, continue the loop.
\n- Return resolved.
\n- Return or throw the last fallback resolution null return or error.
\n- Otherwise, if target is null, return null.
\n- Otherwise throw an Invalid Package Target error.
\n
ESM_FORMAT(url)
\n\n\n\n
\n- Assert: url corresponds to an existing file.
\n- Let pjson be the result of READ_PACKAGE_SCOPE(url).
\n- \n
\nIf url ends in \".mjs\", then
\n\n
\n- Return \"module\".
\n- \n
\nIf url ends in \".cjs\", then
\n\n
\n- Return \"commonjs\".
\n- \n
\nIf pjson?.type exists and is \"module\", then
\n\n
\n- \n
\nIf url ends in \".js\", then
\n\n
\n- Return \"module\".
\n- Throw an Unsupported File Extension error.
\n- \n
\nOtherwise,
\n\n
\n- Throw an Unsupported File Extension error.
\n
READ_PACKAGE_SCOPE(url)
\n\n\n\n
\n- Let scopeURL be url.
\n- \n
\nWhile scopeURL is not the file system root,
\n\n
\n- Set scopeURL to the parent URL of scopeURL.
\n- If scopeURL ends in a \"node_modules\" path segment, return null.
\n- Let pjson be the result of READ_PACKAGE_JSON(scopeURL).
\n- \n
\nIf pjson is not null, then
\n\n
\n- Return pjson.
\n- Return null.
\n
READ_PACKAGE_JSON(packageURL)
\n\n\n\n
\n- Let pjsonURL be the resolution of \"package.json\" within packageURL.
\n- \n
\nIf the file at pjsonURL does not exist, then
\n\n
\n- Return null.
\n- \n
\nIf the file at packageURL does not parse as valid JSON, then
\n\n
\n- Throw an Invalid Package Configuration error.
\n- Return the parsed JSON source of the file at pjsonURL.
\n
The current specifier resolution does not support all default behavior of\nthe CommonJS loader. One of the behavior differences is automatic resolution\nof file extensions and the ability to import directories that have an index\nfile.
\nThe --experimental-specifier-resolution=[mode]
flag can be used to customize\nthe extension resolution algorithm. The default mode is explicit
, which\nrequires the full path to a module be provided to the loader. To enable the\nautomatic extension resolution and importing from directories that include an\nindex file use the node
mode.
$ node index.mjs\nsuccess!\n$ node index # Failure!\nError: Cannot find module\n$ node --experimental-specifier-resolution=node index\nsuccess!\n
",
"type": "module",
"displayName": "Customizing ESM specifier resolution algorithm"
}
],
"type": "misc",
"displayName": "Resolution algorithm"
}
],
"properties": [
{
"textRaw": "`meta` {Object}",
"type": "Object",
"name": "meta",
"desc": "The import.meta
metaproperty is an Object
that contains the following\nproperty:
url
<string> The absolute file:
URL of the module.