{ "type": "module", "source": "doc/api/esm.md", "introduced_in": "v8.5.0", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v18.20.0", "pr-url": "https://github.com/nodejs/node/pull/50140", "description": "Add experimental support for import attributes." }, { "version": "v18.19.0", "pr-url": "https://github.com/nodejs/node/pull/44710", "description": "Module customization hooks are executed off the main thread." }, { "version": [ "v18.6.0" ], "pr-url": "https://github.com/nodejs/node/pull/42623", "description": "Add support for chaining module customization hooks." }, { "version": [ "v17.1.0", "v16.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/40250", "description": "Add experimental support for import assertions." }, { "version": [ "v17.0.0", "v16.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/37468", "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." }, { "version": [ "v15.3.0", "v14.17.0", "v12.22.0" ], "pr-url": "https://github.com/nodejs/node/pull/35781", "description": "Stabilize modules implementation." }, { "version": [ "v14.13.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/35249", "description": "Support for detection of CommonJS named exports." }, { "version": "v14.8.0", "pr-url": "https://github.com/nodejs/node/pull/34558", "description": "Unflag Top-Level Await." }, { "version": [ "v14.0.0", "v13.14.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/31974", "description": "Remove experimental modules warning." }, { "version": [ "v13.2.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/29866", "description": "Loading ECMAScript modules no longer requires a command-line flag." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26745", "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." } ] }, "stability": 2, "stabilityText": "Stable", "properties": [ { "textRaw": "`meta` {Object}", "type": "Object", "name": "meta", "desc": "
The import.meta
meta property is an Object
that contains the following\nproperties.
This is defined exactly the same as it is in browsers providing the URL of the\ncurrent module file.
\nThis enables useful patterns such as relative file loading:
\nimport { readFileSync } from 'node:fs';\nconst buffer = readFileSync(new URL('./data.proto', import.meta.url));\n
",
"shortDesc": "The absolute `file:` URL of the module."
}
],
"methods": [
{
"textRaw": "`import.meta.resolve(specifier)`",
"type": "method",
"name": "resolve",
"meta": {
"added": [
"v13.9.0",
"v12.16.2"
],
"changes": [
{
"version": "v18.19.0",
"pr-url": "https://github.com/nodejs/node/pull/49028",
"description": "Unflag `import.meta.resolve``, with `parentURL` parameter still flagged."
},
{
"version": "v18.19.0",
"pr-url": "https://github.com/nodejs/node/pull/49038",
"description": "This API no longer throws when targeting `file:` URLs that do not map to an existing file on the local FS."
},
{
"version": "v18.19.0",
"pr-url": "https://github.com/nodejs/node/pull/44710",
"description": "This API now returns a string synchronously instead of a Promise."
},
{
"version": [
"v16.2.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38587",
"description": "Add support for WHATWG `URL` object to `parentURL` parameter."
}
]
},
"stability": 1,
"stabilityText": ".2 - Release candidate",
"signatures": [
{
"return": {
"textRaw": "Returns: {string} The absolute URL string that the specifier would resolve to.",
"name": "return",
"type": "string",
"desc": "The absolute URL string that the specifier would resolve to."
},
"params": [
{
"textRaw": "`specifier` {string} The module specifier to resolve relative to the current module.",
"name": "specifier",
"type": "string",
"desc": "The module specifier to resolve relative to the current module."
}
]
}
],
"desc": "import.meta.resolve
is a module-relative resolution function scoped to\neach module, returning the URL string.
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\n
\nAll features of the Node.js module resolution are supported. Dependency\nresolutions are subject to the permitted exports resolutions within the package.
\nCaveats:
\nrequire.resolve
.Non-standard API:
\nWhen using the --experimental-import-meta-resolve
flag, that function accepts\na second argument:
parent
<string> | <URL> An optional absolute parent module URL to resolve from.\nDefault: import.meta.url
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 interoperability between them and its original module format,\nCommonJS.
\n\n", "type": "misc", "displayName": "esm" }, { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "
Node.js has two module systems: CommonJS modules and ECMAScript modules.
\nAuthors can tell Node.js to use the ECMAScript modules loader via the .mjs
\nfile extension, the package.json
\"type\"
field, the --input-type
\nflag, or the --experimental-default-type
flag. Outside of those cases,\nNode.js will use the CommonJS module loader. See Determining module system\nfor more details.
" }, { "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. 'node:path'
in import { sep } from 'node:path'
. Specifiers are also\nused in export from
statements, and as the argument to an import()
\nexpression.
There are three types of specifiers:
\nRelative specifiers like './startup.js'
or '../config.mjs'
. They refer\nto a path relative to the location of the importing file. The file extension\nis always necessary for these.
Bare specifiers like 'some-package'
or 'some-package/shuffle'
. They can\nrefer to the main entry point of a package by the package name, or a\nspecific feature module within a package prefixed by the package name as per\nthe examples respectively. Including the file extension is only necessary\nfor packages without an \"exports\"
field.
Absolute specifiers like 'file:///opt/nodejs/config.js'
. They refer\ndirectly and explicitly to a full path.
Bare specifier resolutions are handled by the Node.js module\nresolution and loading algorithm.\nAll other specifier resolutions are always only resolved with\nthe standard relative URL resolution semantics.
\nLike in CommonJS, module files within packages can be accessed by appending a\npath to the package name unless the package's package.json
contains an\n\"exports\"
field, in which case files within packages can only be accessed\nvia the paths defined in \"exports\"
.
For details on these package resolution rules that apply to bare specifiers in\nthe Node.js module resolution, see the packages documentation.
", "type": "module", "displayName": "Terminology" }, { "textRaw": "Mandatory file extensions", "name": "mandatory_file_extensions", "desc": "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.
This behavior matches how import
behaves in browser environments, assuming a\ntypically configured server.
ES modules are resolved and cached as URLs. This means that special characters\nmust be percent-encoded, such as #
with %23
and ?
with %3F
.
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.
Modules are loaded multiple times if the import
specifier used to resolve\nthem has 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
\nThe volume root may be referenced via /
, //
, or file:///
. Given the\ndifferences between URL and path resolution (such as percent encoding\ndetails), it is recommended to use url.pathToFileURL when importing a path.
data:
URLs are supported for importing with the following MIME types:
text/javascript
for ES modulesapplication/json
for JSONapplication/wasm
for Wasmimport 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"' with { type: 'json' };\n
\ndata:
URLs only resolve bare specifiers for builtin modules\nand absolute specifiers. Resolving\nrelative specifiers does not work because data:
is not a\nspecial 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.
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.
import fs from 'node:fs/promises';\n
\n",
"type": "module",
"displayName": "`node:` imports"
}
],
"type": "module",
"displayName": "URLs"
}
],
"type": "misc",
"displayName": "`import` Specifiers"
},
{
"textRaw": "Import attributes",
"name": "import_attributes",
"meta": {
"added": [
"v17.1.0",
"v16.14.0"
],
"changes": [
{
"version": "v18.20.0",
"pr-url": "https://github.com/nodejs/node/pull/50140",
"description": "Switch from Import Assertions to Import Attributes."
}
]
},
"stability": 1,
"stabilityText": ".1 - Active development",
"desc": "\n\nThis feature was previously named \"Import assertions\", and using the
\nassert
\nkeyword instead ofwith
. Any uses in code of the priorassert
keyword\nshould be updated to usewith
instead.
The Import Attributes proposal adds an inline syntax for module import\nstatements to pass on more information alongside the module specifier.
\nimport fooData from './foo.json' with { type: 'json' };\n\nconst { default: barData } =\n await import('./bar.json', { with: { type: 'json' } });\n
\nNode.js supports the following type
values, for which the attribute is\nmandatory:
Attribute type | \nNeeded for | \n
---|---|
'json' | \nJSON modules | \n
Core 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 builtin modules are updated only by calling\nmodule.syncBuiltinESMExports()
.
import EventEmitter from 'node:events';\nconst e = new EventEmitter();\n
\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
\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
",
"type": "misc",
"displayName": "Builtin modules"
},
{
"textRaw": "`import()` expressions",
"name": "`import()`_expressions",
"desc": "Dynamic import()
is supported in both CommonJS and ES modules. In CommonJS\nmodules it can be used to load ES modules.
An import
statement can reference an ES module or a CommonJS module.\nimport
statements are permitted only in ES modules, but dynamic import()
\nexpressions are supported in CommonJS for loading ES modules.
When importing CommonJS modules, the\nmodule.exports
object is provided as the default export. Named exports may be\navailable, provided by static analysis as a convenience for better ecosystem\ncompatibility.
The CommonJS module require
always treats the files it references as CommonJS.
Using require
to load an ES module is not supported because ES modules have\nasynchronous execution. Instead, use import()
to load an ES module\nfrom a CommonJS module.
CommonJS modules consist of a module.exports
object which can be of any type.
When importing a CommonJS module, it can be reliably imported using the ES\nmodule default import or its corresponding sugar syntax:
\n\nimport { default as cjs } from 'cjs';\n\n// The following import statement is \"syntax sugar\" (equivalent but sweeter)\n// for `{ default as cjsSugar }` in the above import statement:\nimport cjsSugar from 'cjs';\n\nconsole.log(cjs);\nconsole.log(cjs === cjsSugar);\n// Prints:\n// <module.exports>\n// true\n
\nThe ECMAScript Module Namespace representation of a CommonJS module is always\na namespace with a default
export key pointing to the CommonJS\nmodule.exports
value.
This Module Namespace Exotic Object can be directly observed either when using\nimport * as m from 'cjs'
or a dynamic import:
import * as m from 'cjs';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n// [Module] { default: <module.exports> }\n// true\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.
\nFor example, consider a CommonJS module written:
\n// cjs.cjs\nexports.name = 'exported';\n
\nThe preceding module supports named imports in ES modules:
\n\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: [Module] { default: { name: 'exported' }, name: 'exported' }\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.
Live binding updates or new exports added to module.exports
are not detected\nfor these named exports.
The 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.
\nNamed exports detection covers many common export patterns, reexport patterns\nand build tool and transpiler outputs. See cjs-module-lexer for the exact\nsemantics implemented.
", "type": "module", "displayName": "CommonJS Namespaces" }, { "textRaw": "Differences between ES modules and CommonJS", "name": "differences_between_es_modules_and_commonjs", "modules": [ { "textRaw": "No `require`, `exports`, or `module.exports`", "name": "no_`require`,_`exports`,_or_`module.exports`", "desc": "In most cases, the ES module import
can be used to load CommonJS modules.
If needed, a require
function can be constructed within an ES module using\nmodule.createRequire()
.
These CommonJS variables are not available in ES modules.
\n__filename
and __dirname
use cases can be replicated via\nimport.meta.url
.
Addons are not currently supported with ES module imports.
\nThey can instead be loaded with module.createRequire()
or\nprocess.dlopen
.
Relative resolution can be handled via new URL('./local', import.meta.url)
.
For a complete require.resolve
replacement, there is the\nimport.meta.resolve API.
Alternatively module.createRequire()
can be used.
NODE_PATH
is not part of resolving import
specifiers. Please use symlinks\nif this behavior is desired.
require.extensions
is not used by import
. Module customization hooks can\nprovide a replacement.
require.cache
is not used by import
as the ES module loader has its own\nseparate cache.
", "type": "module", "displayName": "No `require.cache`" } ], "type": "module", "displayName": "Differences between ES modules and CommonJS" } ], "type": "misc", "displayName": "Interoperability with CommonJS" }, { "textRaw": "JSON modules", "name": "json_modules", "stability": 1, "stabilityText": "Experimental", "desc": "
JSON files can be referenced by import
:
import packageConfig from './package.json' with { type: 'json' };\n
\nThe with { type: 'json' }
syntax is mandatory; see Import Attributes.
The 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.
", "type": "misc", "displayName": "JSON modules" }, { "textRaw": "Wasm modules", "name": "wasm_modules", "stability": 1, "stabilityText": "Experimental", "desc": "
Importing WebAssembly 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 WebAssembly.
\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
.
", "type": "misc", "displayName": "Wasm modules" }, { "textRaw": "Top-level `await`", "name": "top-level_`await`", "meta": { "added": [ "v14.8.0" ], "changes": [] }, "desc": "
The await
keyword may be used in the top level body of an ECMAScript module.
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
\nIf a top level await
expression never resolves, the node
process will exit\nwith a 13
status 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});\n
",
"type": "misc",
"displayName": "Top-level `await`"
},
{
"textRaw": "HTTPS and HTTP imports",
"name": "https_and_http_imports",
"stability": 1,
"stabilityText": "Experimental",
"desc": "Importing network based modules using https:
and http:
is supported under\nthe --experimental-network-imports
flag. This allows web browser-like imports\nto work in Node.js with a few differences due to application stability and\nsecurity concerns that are different when running in a privileged environment\ninstead of a browser sandbox.
Automatic protocol negotiation for HTTP/2 and HTTP/3 is not yet supported.
", "type": "module", "displayName": "Imports are limited to HTTP/1" }, { "textRaw": "HTTP is limited to loopback addresses", "name": "http_is_limited_to_loopback_addresses", "desc": "http:
is vulnerable to man-in-the-middle attacks and is not allowed to be\nused for addresses outside of the IPv4 address 127.0.0.0/8
(127.0.0.1
to\n127.255.255.255
) and the IPv6 address ::1
. Support for http:
is intended\nto be used for local development.
Authorization
, Cookie
, and Proxy-Authorization
headers are not sent to the\nserver. Avoid including user info in parts of imported URLs. A security model\nfor safely using these on the server is being worked on.
CORS is designed to allow a server to limit the consumers of an API to a\nspecific set of hosts. This is not supported as it does not make sense for a\nserver-based implementation.
", "type": "module", "displayName": "CORS is never checked on the destination server" }, { "textRaw": "Cannot load non-network dependencies", "name": "cannot_load_non-network_dependencies", "desc": "These modules cannot access other modules that are not over http:
or https:
.\nTo still access local modules while avoiding the security concern, pass in\nreferences to the local dependencies:
// file.mjs\nimport worker_threads from 'node:worker_threads';\nimport { configure, resize } from 'https://example.com/imagelib.mjs';\nconfigure({ worker_threads });\n
\n// https://example.com/imagelib.mjs\nlet worker_threads;\nexport function configure(opts) {\n worker_threads = opts.worker_threads;\n}\nexport function resize(img, size) {\n // Perform resizing in worker_thread to avoid main thread blocking\n}\n
",
"type": "module",
"displayName": "Cannot load non-network dependencies"
},
{
"textRaw": "Network-based loading is not enabled by default",
"name": "network-based_loading_is_not_enabled_by_default",
"desc": "For now, the --experimental-network-imports
flag is required to enable loading\nresources over http:
or https:
. In the future, a different mechanism will be\nused to enforce this. Opt-in is required to prevent transitive dependencies\ninadvertently using potentially mutable state that could affect reliability\nof Node.js applications.
", "type": "module", "displayName": "Network-based loading is not enabled by default" } ], "type": "misc", "displayName": "HTTPS and HTTP imports" }, { "textRaw": "Loaders", "name": "loaders", "desc": "
The former Loaders documentation is now at\nModules: Customization hooks.
", "type": "misc", "displayName": "Loaders" }, { "textRaw": "Resolution and loading algorithm", "name": "resolution_and_loading_algorithm", "modules": [ { "textRaw": "Features", "name": "features", "desc": "The default resolver has the following properties:
\nThe default loader has the following properties
\nnode:
URLsdata:
URLsfile:
module loadingfile:
loading\n(supports only .cjs
, .js
, and .mjs
)The 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 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:
, node:
, or if --experimental-network-imports
\nis enabled, https:
).
The 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.
The 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.
\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- If specifier is a valid URL, then\n
\n\n
\n- Set resolved to the result of parsing and reserializing\nspecifier as a URL.
\n- Otherwise, if specifier starts with \"/\", \"./\", or \"../\", then\n
\n\n
\n- Set resolved to the URL resolution of specifier relative to\nparentURL.
\n- Otherwise, if specifier starts with \"#\", then\n
\n\n
\n- Set resolved to the result of\nPACKAGE_IMPORTS_RESOLVE(specifier,\nparentURL, defaultConditions).
\n- Otherwise,\n
\n\n
\n- Note: specifier is now a bare specifier.
\n- Set resolved the result of\nPACKAGE_RESOLVE(specifier, parentURL).
\n- Let format be undefined.
\n- If resolved is a \"file:\" URL, then\n
\n\n
\n- If resolved contains any percent encodings of \"/\" or \"\\\" (\"%2F\"\nand \"%5C\" respectively), then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- If the file at resolved is a directory, then\n
\n\n
\n- Throw an Unsupported Directory Import error.
\n- If the file at resolved does not exist, then\n
\n\n
\n- Throw a Module Not Found error.
\n- Set resolved to the real path of resolved, maintaining the\nsame URL querystring and fragment components.
\n- Set format to the result of ESM_FILE_FORMAT(resolved).
\n- Otherwise,\n
\n\n
\n- Set format the module format of the content type associated with the\nURL resolved.
\n- Return format and resolved to the loading phase
\n
PACKAGE_RESOLVE(packageSpecifier, parentURL)
\n\n\n\n
\n- Let packageName be undefined.
\n- If packageSpecifier is an empty string, then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- If packageSpecifier is a Node.js builtin module name, then\n
\n\n
\n- Return the string \"node:\" concatenated with packageSpecifier.
\n- If packageSpecifier does not start with \"@\", then\n
\n\n
\n- Set packageName to the substring of packageSpecifier until the first\n\"/\" separator or the end of the string.
\n- Otherwise,\n
\n\n
\n- If packageSpecifier does not contain a \"/\" separator, then\n
\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- If packageName starts with \".\" or contains \"\\\" or \"%\", then\n
\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- If packageSubpath ends in \"/\", then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Let selfUrl be the result of\nPACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
\n- If selfUrl is not undefined, return selfUrl.
\n- While parentURL is not the file system root,\n
\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- If the folder at packageURL does not exist, then\n
\n\n
\n- Continue the next loop iteration.
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- If pjson is not null and pjson.exports is not null or\nundefined, then\n
\n\n
\n- Return the result of PACKAGE_EXPORTS_RESOLVE(packageURL,\npackageSubpath, pjson.exports, defaultConditions).
\n- Otherwise, if packageSubpath is equal to \".\", then\n
\n\n
\n- If pjson.main is a string, then\n
\n\n
\n- Return the URL resolution of main in packageURL.
\n- Otherwise,\n
\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 LOOKUP_PACKAGE_SCOPE(parentURL).
\n- If packageURL is null, then\n
\n\n
\n- Return undefined.
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- If pjson is null or if pjson.exports is null or\nundefined, then\n
\n\n
\n- Return undefined.
\n- If pjson.name is equal to packageName, then\n
\n\n
\n- Return the result of PACKAGE_EXPORTS_RESOLVE(packageURL,\npackageSubpath, pjson.exports, defaultConditions).
\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- If subpath is equal to \".\", then\n
\n\n
\n- Let mainExport be undefined.
\n- If exports is a String or Array, or an Object containing no keys\nstarting with \".\", then\n
\n\n
\n- Set mainExport to exports.
\n- Otherwise if exports is an Object containing a \".\" property, then\n
\n\n
\n- Set mainExport to exports[\".\"].
\n- If mainExport is not undefined, then\n
\n\n
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, null, false, conditions).
\n- If resolved is not null or undefined, return resolved.
\n- Otherwise, if exports is an Object and all keys of exports start with\n\".\", then\n
\n\n
\n- Let matchKey be the string \"./\" concatenated with subpath.
\n- Let resolved be the result of PACKAGE_IMPORTS_EXPORTS_RESOLVE(\nmatchKey, exports, packageURL, false, conditions).
\n- If resolved is not null or undefined, return resolved.
\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- If specifier is exactly equal to \"#\" or starts with \"#/\", then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(parentURL).
\n- If packageURL is not null, then\n
\n\n
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- If pjson.imports is a non-null Object, then\n
\n\n
\n- Let resolved be the result of\nPACKAGE_IMPORTS_EXPORTS_RESOLVE(\nspecifier, pjson.imports, packageURL, true, conditions).
\n- If resolved is not null or undefined, return resolved.
\n- Throw a Package Import Not Defined error.
\n
PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL,\nisImports, conditions)
\n\n\n\n
\n- If matchKey is a key of matchObj and does not contain \"*\", then\n
\n\n
\n- Let target be the value of matchObj[matchKey].
\n- Return the result of PACKAGE_TARGET_RESOLVE(packageURL,\ntarget, null, isImports, conditions).
\n- Let expansionKeys be the list of keys of matchObj containing only a\nsingle \"*\", sorted by the sorting function PATTERN_KEY_COMPARE\nwhich orders in descending order of specificity.
\n- For each key expansionKey in expansionKeys, do\n
\n\n
\n- Let patternBase be the substring of expansionKey up to but excluding\nthe first \"*\" character.
\n- If matchKey starts with but is not equal to patternBase, then\n
\n\n
\n- Let patternTrailer be the substring of expansionKey from the\nindex after the first \"*\" character.
\n- If patternTrailer has zero length, or if matchKey ends with\npatternTrailer and the length of matchKey is greater than or\nequal to the length of expansionKey, then\n
\n\n
\n- Let target be the value of matchObj[expansionKey].
\n- Let patternMatch be the substring of matchKey starting at the\nindex of the length of patternBase up to the length of\nmatchKey minus the length of patternTrailer.
\n- Return the result of PACKAGE_TARGET_RESOLVE(packageURL,\ntarget, patternMatch, isImports, conditions).
\n- Return null.
\n
PATTERN_KEY_COMPARE(keyA, keyB)
\n\n\n\n
\n- Assert: keyA ends with \"/\" or contains only a single \"*\".
\n- Assert: keyB ends with \"/\" or contains only a single \"*\".
\n- Let baseLengthA be the index of \"*\" in keyA plus one, if keyA\ncontains \"*\", or the length of keyA otherwise.
\n- Let baseLengthB be the index of \"*\" in keyB plus one, if keyB\ncontains \"*\", or the length of keyB otherwise.
\n- If baseLengthA is greater than baseLengthB, return -1.
\n- If baseLengthB is greater than baseLengthA, return 1.
\n- If keyA does not contain \"*\", return 1.
\n- If keyB does not contain \"*\", return -1.
\n- If the length of keyA is greater than the length of keyB, return -1.
\n- If the length of keyB is greater than the length of keyA, return 1.
\n- Return 0.
\n
PACKAGE_TARGET_RESOLVE(packageURL, target, patternMatch,\nisImports, conditions)
\n\n\n\n
\n- If target is a String, then\n
\n\n
\n- If target does not start with \"./\", then\n
\n\n
\n- If isImports is false, or if target starts with \"../\" or\n\"/\", or if target is a valid URL, then\n
\n\n
\n- Throw an Invalid Package Target error.
\n- If patternMatch is a String, then\n
\n\n
\n- Return PACKAGE_RESOLVE(target with every instance of \"*\"\nreplaced by patternMatch, packageURL + \"/\").
\n- Return PACKAGE_RESOLVE(target, packageURL + \"/\").
\n- If target split on \"/\" or \"\\\" contains any \"\", \".\", \"..\",\nor \"node_modules\" segments after the first \".\" segment, case\ninsensitive and including percent encoded variants, throw an Invalid\nPackage Target error.
\n- Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
\n- Assert: resolvedTarget is contained in packageURL.
\n- If patternMatch is null, then\n
\n\n
\n- Return resolvedTarget.
\n- If patternMatch split on \"/\" or \"\\\" contains any \"\", \".\",\n\"..\", or \"node_modules\" segments, case insensitive and including\npercent encoded variants, throw an Invalid Module Specifier error.
\n- Return the URL resolution of resolvedTarget with every instance of\n\"*\" replaced with patternMatch.
\n- Otherwise, if target is a non-null Object, then\n
\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- For each property p of target, in object insertion order as,\n
\n\n
\n- If p equals \"default\" or conditions contains an entry for p,\nthen\n
\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, patternMatch, isImports,\nconditions).
\n- If resolved is equal to undefined, continue the loop.
\n- Return resolved.
\n- Return undefined.
\n- Otherwise, if target is an Array, then\n
\n\n
\n- If _target.length is zero, return null.
\n- For each item targetValue in target, do\n
\n\n
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, patternMatch, isImports,\nconditions), continuing the loop on any Invalid Package Target\nerror.
\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_FILE_FORMAT(url)
\n\n\n\n
\n- Assert: url corresponds to an existing file.
\n- If url ends in \".mjs\", then\n
\n\n
\n- Return \"module\".
\n- If url ends in \".cjs\", then\n
\n\n
\n- Return \"commonjs\".
\n- If url ends in \".json\", then\n
\n\n
\n- Return \"json\".
\n- Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(url).
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- If pjson?.type exists and is \"module\", then\n
\n\n
\n- If url ends in \".js\" or has no file extension, then\n
\n\n
\n- If
\n--experimental-wasm-modules
is enabled and the file at url\ncontains the header for a WebAssembly module, then\n\n
\n- Return \"wasm\".
\n- Otherwise,\n
\n\n
\n- Return \"module\".
\n- Return undefined.
\n- Otherwise,\n
\n\n
\n- Return undefined.
\n
LOOKUP_PACKAGE_SCOPE(url)
\n\n\n\n
\n- Let scopeURL be url.
\n- While scopeURL is not the file system root,\n
\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 pjsonURL be the resolution of \"package.json\" within\nscopeURL.
\n- if the file at pjsonURL exists, then\n
\n\n
\n- Return scopeURL.
\n- Return null.
\n
READ_PACKAGE_JSON(packageURL)
\n\n", "type": "module", "displayName": "Resolution Algorithm Specification" }, { "textRaw": "Customizing ESM specifier resolution algorithm", "name": "customizing_esm_specifier_resolution_algorithm", "stability": 1, "stabilityText": "Experimental", "desc": "\n
\n- Let pjsonURL be the resolution of \"package.json\" within packageURL.
\n- If the file at pjsonURL does not exist, then\n
\n\n
\n- Return null.
\n- If the file at packageURL does not parse as valid JSON, then\n
\n\n
\n- Throw an Invalid Package Configuration error.
\n- Return the parsed JSON source of the file at pjsonURL.
\n
\n\nDo not rely on this flag. We plan to remove it once the\nModule customization hooks have advanced to the point that equivalent\nfunctionality can be achieved via custom hooks.
\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
\n",
"type": "module",
"displayName": "Customizing ESM specifier resolution algorithm"
}
],
"type": "misc",
"displayName": "Resolution and loading algorithm"
}
],
"properties": [
{
"textRaw": "`meta` {Object}",
"type": "Object",
"name": "meta",
"desc": "The import.meta
meta property is an Object
that contains the following\nproperties.
This is defined exactly the same as it is in browsers providing the URL of the\ncurrent module file.
\nThis enables useful patterns such as relative file loading:
\nimport { readFileSync } from 'node:fs';\nconst buffer = readFileSync(new URL('./data.proto', import.meta.url));\n
",
"shortDesc": "The absolute `file:` URL of the module."
}
],
"methods": [
{
"textRaw": "`import.meta.resolve(specifier)`",
"type": "method",
"name": "resolve",
"meta": {
"added": [
"v13.9.0",
"v12.16.2"
],
"changes": [
{
"version": "v18.19.0",
"pr-url": "https://github.com/nodejs/node/pull/49028",
"description": "Unflag `import.meta.resolve``, with `parentURL` parameter still flagged."
},
{
"version": "v18.19.0",
"pr-url": "https://github.com/nodejs/node/pull/49038",
"description": "This API no longer throws when targeting `file:` URLs that do not map to an existing file on the local FS."
},
{
"version": "v18.19.0",
"pr-url": "https://github.com/nodejs/node/pull/44710",
"description": "This API now returns a string synchronously instead of a Promise."
},
{
"version": [
"v16.2.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38587",
"description": "Add support for WHATWG `URL` object to `parentURL` parameter."
}
]
},
"stability": 1,
"stabilityText": ".2 - Release candidate",
"signatures": [
{
"return": {
"textRaw": "Returns: {string} The absolute URL string that the specifier would resolve to.",
"name": "return",
"type": "string",
"desc": "The absolute URL string that the specifier would resolve to."
},
"params": [
{
"textRaw": "`specifier` {string} The module specifier to resolve relative to the current module.",
"name": "specifier",
"type": "string",
"desc": "The module specifier to resolve relative to the current module."
}
]
}
],
"desc": "import.meta.resolve
is a module-relative resolution function scoped to\neach module, returning the URL string.
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\n
\nAll features of the Node.js module resolution are supported. Dependency\nresolutions are subject to the permitted exports resolutions within the package.
\nCaveats:
\nrequire.resolve
.Non-standard API:
\nWhen using the --experimental-import-meta-resolve
flag, that function accepts\na second argument: