{ "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.
Node.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.
", "type": "misc", "displayName": "esm" }, { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "The --experimental-modules
flag can be used to enable support for\nECMAScript modules (ES modules).
Once enabled, Node.js will treat the following as ES modules when passed to\nnode
as the initial input, or when referenced by import
statements within\nES module code:
Files ending in .mjs
.
Files ending in .js
, or extensionless files, when the nearest parent\npackage.json
file contains a top-level field \"type\"
with a value of\n\"module\"
.
Strings passed in as an argument to --eval
or --print
, or piped to\nnode
via STDIN
, with the flag --input-type=module
.
Node.js will treat as CommonJS all other forms of input, such as .js
files\nwhere the nearest parent package.json
file contains no top-level \"type\"
\nfield, or string input without the flag --input-type
. This behavior is to\npreserve backward compatibility. However, now that Node.js supports both\nCommonJS and ES modules, it is best to be explicit whenever possible. Node.js\nwill treat the following as CommonJS when passed to node
as the initial input,\nor when referenced by import
statements within ES module code:
Files ending in .cjs
.
Files ending in .js
, or extensionless files, when the nearest parent\npackage.json
file contains a top-level field \"type\"
with a value of\n\"commonjs\"
.
Strings passed in as an argument to --eval
or --print
, or piped to\nnode
via STDIN
, with the flag --input-type=commonjs
.
package.json
\"type\"
field",
"name": "package.json
_\"type\"
_field",
"desc": "Files ending with .js
or .mjs
, or lacking any extension,\nwill be loaded as ES modules when the nearest parent package.json
file\ncontains a top-level field \"type\"
with a value of \"module\"
.
The nearest parent package.json
is defined as the first package.json
found\nwhen searching in the current folder, that folder’s parent, and so on up\nuntil the root of the volume is reached.
// package.json\n{\n \"type\": \"module\"\n}\n
\n# In same folder as above package.json\nnode --experimental-modules my-app.js # Runs as ES module\n
\nIf the nearest parent package.json
lacks a \"type\"
field, or contains\n\"type\": \"commonjs\"
, extensionless and .js
files are treated as CommonJS.\nIf the volume root is reached and no package.json
is found,\nNode.js defers to the default, a package.json
with no \"type\"
\nfield.
import
statements of .js
and extensionless files are treated as ES modules\nif the nearest parent package.json
contains \"type\": \"module\"
.
// my-app.js, part of the same example as above\nimport './startup.js'; // Loaded as ES module because of package.json\n
\nPackage authors should include the \"type\"
field, even in packages where all\nsources are CommonJS. Being explicit about the type
of the package will\nfuture-proof the package in case the default type of Node.js ever changes, and\nit will also make things easier for build tools and loaders to determine how the\nfiles in the package should be interpreted.
package.json
\"type\"
field"
},
{
"textRaw": "Package Scope and File Extensions",
"name": "package_scope_and_file_extensions",
"desc": "A folder containing a package.json
file, and all subfolders below that\nfolder down until the next folder containing another package.json
, is\nconsidered a package scope. The \"type\"
field defines how .js
and\nextensionless files should be treated within a particular package.json
file’s\npackage scope. Every package in a project’s node_modules
folder contains its\nown package.json
file, so each project’s dependencies have their own package\nscopes. A package.json
lacking a \"type\"
field is treated as if it contained\n\"type\": \"commonjs\"
.
The package scope applies not only to initial entry points (node --experimental-modules my-app.js
) but also to files referenced by import
\nstatements and import()
expressions.
// my-app.js, in an ES module package scope because there is a package.json\n// file in the same folder with \"type\": \"module\".\n\nimport './startup/init.js';\n// Loaded as ES module since ./startup contains no package.json file,\n// and therefore inherits the ES module package scope from one level up.\n\nimport 'commonjs-package';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n\nimport './node_modules/commonjs-package/index.js';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n
\nFiles ending with .mjs
are always loaded as ES modules regardless of package\nscope.
Files ending with .cjs
are always loaded as CommonJS regardless of package\nscope.
import './legacy-file.cjs';\n// Loaded as CommonJS since .cjs is always loaded as CommonJS.\n\nimport 'commonjs-package/src/index.mjs';\n// Loaded as ES module since .mjs is always loaded as ES module.\n
\nThe .mjs
and .cjs
extensions may be used to mix types within the same\npackage scope:
Within a \"type\": \"module\"
package scope, Node.js can be instructed to\ninterpret a particular file as CommonJS by naming it with a .cjs
extension\n(since both .js
and .mjs
files are treated as ES modules within a\n\"module\"
package scope).
Within a \"type\": \"commonjs\"
package scope, Node.js can be instructed to\ninterpret a particular file as an ES module by naming it with an .mjs
\nextension (since both .js
and .cjs
files are treated as CommonJS within a\n\"commonjs\"
package scope).
--input-type
flag",
"name": "--input-type
_flag",
"desc": "Strings passed in as an argument to --eval
or --print
(or -e
or -p
), or\npiped to node
via STDIN
, will be treated as ES modules when the\n--input-type=module
flag is set.
node --experimental-modules --input-type=module --eval \\\n \"import { sep } from 'path'; console.log(sep);\"\n\necho \"import { sep } from 'path'; console.log(sep);\" | \\\n node --experimental-modules --input-type=module\n
\nFor completeness there is also --input-type=commonjs
, for explicitly running\nstring input as CommonJS. This is the default behavior if --input-type
is\nunspecified.
--input-type
flag"
}
]
},
{
"textRaw": "Packages",
"name": "packages",
"modules": [
{
"textRaw": "Package Entry Points",
"name": "package_entry_points",
"desc": "The package.json
\"main\"
field defines the entry point for a package,\nwhether the package is included into CommonJS via require
or into an ES\nmodule via import
.
// ./node_modules/es-module-package/package.json\n{\n \"type\": \"module\",\n \"main\": \"./src/index.js\"\n}\n
\n// ./my-app.mjs\n\nimport { something } from 'es-module-package';\n// Loads from ./node_modules/es-module-package/src/index.js\n
\nAn attempt to require
the above es-module-package
would attempt to load\n./node_modules/es-module-package/src/index.js
as CommonJS, which would throw\nan error as Node.js would not be able to parse the export
statement in\nCommonJS.
As with import
statements, for ES module usage the value of \"main\"
must be\na full path including extension: \"./index.mjs\"
, not \"./index\"
.
If the package.json
\"type\"
field is omitted, a .js
file in \"main\"
will\nbe interpreted as CommonJS.
The \"main\"
field can point to exactly one file, regardless of whether the\npackage is referenced via require
(in a CommonJS context) or import
(in an\nES module context).
Prior to the introduction of support for ES modules in Node.js, it was a common\npattern for package authors to include both CommonJS and ES module JavaScript\nsources in their package, with package.json
\"main\"
specifying the CommonJS\nentry point and package.json
\"module\"
specifying the ES module entry point.\nThis enabled Node.js to run the CommonJS entry point while build tools such as\nbundlers used the ES module entry point, since Node.js ignored (and still\nignores) \"module\"
.
Node.js can now run ES module entry points, but it remains impossible for a\npackage to define separate CommonJS and ES module entry points. This is for good\nreason: the pkg
variable created from import pkg from 'pkg'
is not the same\nsingleton as the pkg
variable created from const pkg = require('pkg')
, so if\nboth are referenced within the same app (including dependencies), unexpected\nbehavior might occur.
There are two general approaches to addressing this limitation while still\npublishing a package that contains both CommonJS and ES module sources:
\nDocument a new ES module entry point that’s not the package \"main\"
, e.g.\nimport pkg from 'pkg/module.mjs'
(or import 'pkg/esm'
, if using package\nexports). The package \"main\"
would still point to a CommonJS file, and\nthus the package would remain compatible with older versions of Node.js that\nlack support for ES modules.
Switch the package \"main\"
entry point to an ES module file as part of a\nbreaking change version bump. This version and above would only be usable on\nES module-supporting versions of Node.js. If the package still contains a\nCommonJS version, it would be accessible via a path within the package, e.g.\nrequire('pkg/commonjs')
; this is essentially the inverse of the previous\napproach. Package consumers who are using CommonJS-only versions of Node.js\nwould need to update their code from require('pkg')
to e.g.\nrequire('pkg/commonjs')
.
Of course, a package could also include only CommonJS or only ES module sources.\nAn existing package could make a semver major bump to an ES module-only version,\nthat would only be supported in ES module-supporting versions of Node.js (and\nother runtimes). New packages could be published containing only ES module\nsources, and would be compatible only with ES module-supporting runtimes.
", "type": "module", "displayName": "Compatibility with CommonJS-Only Versions of Node.js" } ], "type": "module", "displayName": "Package Entry Points" }, { "textRaw": "Package Exports", "name": "package_exports", "desc": "By default, all subpaths from a package can be imported (import 'pkg/x.js'
).\nCustom subpath aliasing and encapsulation can be provided through the\n\"exports\"
field.
// ./node_modules/es-module-package/package.json\n{\n \"exports\": {\n \"./submodule\": \"./src/submodule.js\"\n }\n}\n
\nimport submodule from 'es-module-package/submodule';\n// Loads ./node_modules/es-module-package/src/submodule.js\n
\nIn addition to defining an alias, subpaths not defined by \"exports\"
will\nthrow when an attempt is made to import them:
import submodule from 'es-module-package/private-module.js';\n// Throws - Module not found\n
\n\n\nNote: this is not a strong encapsulation as any private modules can still be\nloaded by absolute paths.
\n
Folders can also be mapped with package exports:
\n\n// ./node_modules/es-module-package/package.json\n{\n \"exports\": {\n \"./features/\": \"./src/features/\"\n }\n}\n
\nimport feature from 'es-module-package/features/x.js';\n// Loads ./node_modules/es-module-package/src/features/x.js\n
\nIf a package has no exports, setting \"exports\": false
can be used instead of\n\"exports\": {}
to indicate the package does not intend for submodules to be\nexposed.
Exports can also be used to map the main entry point of a package:
\n\n// ./node_modules/es-module-package/package.json\n{\n \"exports\": {\n \".\": \"./main.js\"\n }\n}\n
\nwhere the \".\" indicates loading the package without any subpath. Exports will\nalways override any existing \"main\"
value for both CommonJS and\nES module packages.
For packages with only a main entry point, an \"exports\"
value of just\na string is also supported:
// ./node_modules/es-module-package/package.json\n{\n \"exports\": \"./main.js\"\n}\n
\nAny invalid exports entries will be ignored. This includes exports not\nstarting with \"./\"
or a missing trailing \"/\"
for directory exports.
Array fallback support is provided for exports, similarly to import maps\nin order to be forward-compatible with fallback workflows in future:
\n\n{\n \"exports\": {\n \"./submodule\": [\"not:valid\", \"./submodule.js\"]\n }\n}\n
\nSince \"not:valid\"
is not a supported target, \"./submodule.js\"
is used\ninstead as the fallback, as if it were the only target.
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
",
"name": "no_node_path
",
"desc": "NODE_PATH
is not part of resolving import
specifiers. Please use symlinks\nif this behavior is desired.
NODE_PATH
"
},
{
"textRaw": "No require
, exports
, module.exports
, __filename
, __dirname
",
"name": "no_require
,_exports
,_module.exports
,___filename
,___dirname
",
"desc": "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.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.extensions
"
},
{
"textRaw": "No require.cache
",
"name": "no_require.cache
",
"desc": "require.cache
is not used by import
. It has a separate cache.
require.cache
"
},
{
"textRaw": "URL-based paths",
"name": "url-based_paths",
"desc": "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
",
"name": "require
",
"desc": "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()
.
require
"
},
{
"textRaw": "import
statements",
"name": "import
_statements",
"desc": "An import
statement can reference an ES module, a CommonJS module, or JSON.\nOther file types such as Native modules are not supported. For those,\nuse module.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.
\nimport { sin, cos } from 'geometry/trigonometry-functions.mjs';\n
\n\n", "type": "module", "displayName": "Currently only the “default export” is supported for CommonJS files or\npackages:
\n\n\nimport packageMain from 'commonjs-package'; // Works\n\nimport { method } from 'commonjs-package'; // Errors\n
There are ongoing efforts to make the latter code possible.
\n
import
statements"
},
{
"textRaw": "import()
expressions",
"name": "import()
_expressions",
"desc": "Dynamic import()
is supported in both CommonJS and ES modules. It can be used\nto include ES module files from CommonJS code.
(async () => {\n await import('./my-app.mjs');\n})();\n
",
"type": "module",
"displayName": "import()
expressions"
}
],
"type": "misc",
"displayName": "Interoperability with CommonJS"
},
{
"textRaw": "CommonJS, JSON, and Native Modules",
"name": "commonjs,_json,_and_native_modules",
"desc": "CommonJS, JSON, and Native modules can be used with\nmodule.createRequire()
.
// cjs.js\nmodule.exports = 'cjs';\n\n// esm.mjs\nimport { createRequire } from 'module';\nimport { fileURLToPath as fromURL } from 'url';\n\nconst require = createRequire(fromURL(import.meta.url));\n\nconst cjs = require('./cjs');\ncjs === 'cjs'; // true\n
",
"type": "misc",
"displayName": "CommonJS, JSON, and Native Modules"
},
{
"textRaw": "Builtin modules",
"name": "builtin_modules",
"desc": "Builtin modules will provide named exports of their public API, as well as a\ndefault export which can be used for, among other things, modifying the named\nexports. Named exports of builtin modules are updated when the corresponding\nexports property is accessed, redefined, or deleted.
\nimport 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';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\n\nfs.readFileSync === readFileSync;\n
",
"type": "misc",
"displayName": "Builtin modules"
},
{
"textRaw": "JSON Modules",
"name": "json_modules",
"desc": "JSON modules follow the WHATWG JSON modules specification.
\nThe 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
",
"type": "misc",
"displayName": "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-modules --experimental-wasm-modules index.mjs\n
\nwould provide the exports interface for the instantiation of module.wasm
.
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": "Resolve hook", "name": "resolve_hook", "desc": "The resolve hook returns the resolved file URL and module format for a\ngiven module specifier and parent file URL:
\nimport { URL, pathToFileURL } from 'url';\nconst baseURL = pathToFileURL(process.cwd()).href;\n\n/**\n * @param {string} specifier\n * @param {string} parentModuleURL\n * @param {function} defaultResolver\n */\nexport async function resolve(specifier,\n parentModuleURL = baseURL,\n defaultResolver) {\n return {\n url: new URL(specifier, parentModuleURL).href,\n format: 'module'\n };\n}\n
\nThe parentModuleURL
is provided as undefined
when performing main Node.js\nload itself.
The default Node.js ES module resolution function is provided as a third\nargument to the resolver for easy compatibility workflows.
\nIn addition to returning the resolved file URL value, the resolve hook also\nreturns a format
property specifying the module format of the resolved\nmodule. This can be one of the following:
format | \nDescription | \n
---|---|
'builtin' | \nLoad a Node.js builtin module | \n
'commonjs' | \nLoad a Node.js CommonJS module | \n
'dynamic' | \nUse a dynamic instantiate hook | \n
'json' | \nLoad a JSON file | \n
'module' | \nLoad a standard JavaScript module | \n
'wasm' | \nLoad a WebAssembly module | \n
For example, a dummy loader to load JavaScript restricted to browser resolution\nrules with only JS file extension and Node.js builtin modules support could\nbe written:
\nimport path from 'path';\nimport process from 'process';\nimport Module from 'module';\nimport { URL, pathToFileURL } from 'url';\n\nconst builtins = Module.builtinModules;\nconst JS_EXTENSIONS = new Set(['.js', '.mjs']);\n\nconst baseURL = pathToFileURL(process.cwd()).href;\n\n/**\n * @param {string} specifier\n * @param {string} parentModuleURL\n * @param {function} defaultResolver\n */\nexport async function resolve(specifier,\n parentModuleURL = baseURL,\n defaultResolver) {\n if (builtins.includes(specifier)) {\n return {\n url: specifier,\n format: 'builtin'\n };\n }\n if (/^\\.{0,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) {\n // For node_modules support:\n // return defaultResolver(specifier, parentModuleURL);\n throw new Error(\n `imports must begin with '/', './', or '../'; '${specifier}' does not`);\n }\n const resolved = new URL(specifier, parentModuleURL);\n const ext = path.extname(resolved.pathname);\n if (!JS_EXTENSIONS.has(ext)) {\n throw new Error(\n `Cannot load file with non-JavaScript file extension ${ext}.`);\n }\n return {\n url: resolved.href,\n format: 'module'\n };\n}\n
\nWith this loader, running:
\nNODE_OPTIONS='--experimental-modules --experimental-loader ./custom-loader.mjs' node x.js\n
\nwould load the module x.js
as an ES module with relative resolution support\n(with node_modules
loading skipped in this example).
To create a custom dynamic module that doesn't correspond to one of the\nexisting format
interpretations, the dynamicInstantiate
hook can be used.\nThis hook is called only for modules that return format: 'dynamic'
from\nthe resolve
hook.
export async function dynamicInstantiate(url) {\n return {\n exports: ['customExportName'],\n execute: (exports) => {\n // Get and set functions provided for pre-allocated export names\n exports.customExportName.set('value');\n }\n };\n}\n
\nWith the list of module exports provided upfront, the execute
function will\nthen be called at the exact point of module evaluation order for that module\nin the import tree.
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, in addition to the unique module\nformat for that resolved URL given by the ESM_FORMAT routine.
\nThe \"module\" format is returned for an ECMAScript Module, while the\n\"commonjs\" format is used to indicate loading through the legacy\nCommonJS loader. Additional formats such as \"addon\" can be extended in future\nupdates.
\nIn the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.
\nisMain is true when resolving the Node.js application entry point.
\nESM_RESOLVE(specifier, parentURL, isMain)
\n\n\n\n
\n- Let resolvedURL be undefined.
\n- \n
\nIf specifier is a valid URL, then
\n\n
\n- Set resolvedURL to the result of parsing and reserializing\nspecifier as a URL.
\n- \n
\nOtherwise, if specifier starts with \"/\", then
\n\n
\n- Throw an Invalid Specifier error.
\n- \n
\nOtherwise, if specifier starts with \"./\" or \"../\", then
\n\n
\n- Set resolvedURL to the URL resolution of specifier relative to\nparentURL.
\n- \n
\nOtherwise,
\n\n
\n- Note: specifier is now a bare specifier.
\n- Set resolvedURL the result of\nPACKAGE_RESOLVE(specifier, parentURL).
\n- \n
\nIf resolvedURL contains any percent encodings of \"/\" or \"\\\" (\"%2f\"\nand \"%5C\" respectively), then
\n\n
\n- Throw an Invalid Specifier error.
\n- \n
\nIf the file at resolvedURL does not exist, then
\n\n
\n- Throw a Module Not Found error.
\n- Set resolvedURL to the real path of resolvedURL.
\n- Let format be the result of ESM_FORMAT(resolvedURL, isMain).
\n- Load resolvedURL as module format, format.
\n
PACKAGE_RESOLVE(packageSpecifier, parentURL)
\n\n\n\n
\n- Let packageName be undefined.
\n- Let packageSubpath be undefined.
\n- \n
\nIf packageSpecifier is an empty string, then
\n\n
\n- Throw an Invalid Specifier error.
\n- \n
\nIf packageSpecifier does not start with \"@\", then
\n\n
\n- Set packageName to the substring of packageSpecifier until the\nfirst \"/\" 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 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 Specifier error.
\n- Let packageSubpath be undefined.
\n- \n
\nIf the length of packageSpecifier is greater than the length of\npackageName, then
\n\n
\n- Set packageSubpath to \".\" concatenated with the substring of\npackageSpecifier from the position at the length of packageName.
\n- \n
\nIf packageSubpath contains any \".\" or \"..\" segments or percent\nencoded strings for \"/\" or \"\\\" then,
\n\n
\n- Throw an Invalid Specifier error.
\n- \n
\nIf packageSubpath is undefined and packageName is a Node.js builtin\nmodule, then
\n\n
\n- Return the string \"node:\" 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 packageSubpath is _undefined__, then
\n\n
\n- Return the result of PACKAGE_MAIN_RESOLVE(packageURL,\npjson).
\n- \n
\nOtherwise,
\n\n
\n- \n
\nIf pjson is not null and pjson has an \"exports\" key, then
\n\n
\n- Let exports be pjson.exports.
\n- \n
\nIf exports is not null or undefined, then
\n\n
\n- Return PACKAGE_EXPORTS_RESOLVE(packageURL,\npackageSubpath, pjson.exports).
\n- Return the URL resolution of packageSubpath in packageURL.
\n- Throw a Module Not Found error.
\n
PACKAGE_MAIN_RESOLVE(packageURL, pjson)
\n\n\n\n
\n- \n
\nIf pjson is null, then
\n\n
\n- Throw a Module Not Found error.
\n- \n
\nIf pjson.exports is not null or undefined, then
\n\n
\n- \n
\nIf pjson.exports is a String or Array, then
\n\n
\n- Return PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, pjson.exports,\n\"\").
\n- \n
\nIf _pjson.exports is an Object, then
\n\n
\n- \n
\nIf pjson.exports contains a \".\" property, then
\n\n
\n- Let mainExport be the \".\" property in pjson.exports.
\n- Return PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, mainExport,\n\"\").
\n- \n
\nIf pjson.main is a String, then
\n\n
\n- Let resolvedMain be the URL resolution of packageURL, \"/\", and\npjson.main.
\n- \n
\nIf the file at resolvedMain exists, then
\n\n
\n- Return resolvedMain.
\n- \n
\nIf pjson.type is equal to \"module\", then
\n\n
\n- Throw a Module Not Found error.
\n- Let legacyMainURL be the result applying the legacy\nLOAD_AS_DIRECTORY CommonJS resolver to packageURL, throwing a\nModule Not Found error for no resolution.
\n- Return legacyMainURL.
\n
PACKAGE_EXPORTS_RESOLVE(packageURL, packagePath, exports)
\n\n\n\n
\n- \n
\nIf exports is an Object, then
\n\n
\n- Set packagePath to \"./\" concatenated with packagePath.
\n- \n
\nIf packagePath is a key of exports, then
\n\n
\n- Let target be the value of exports[packagePath].
\n- Return PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, target,\n\"\").
\n- Let directoryKeys be the list of keys of exports ending in\n\"/\", sorted by length descending.
\n- \n
\nFor each key directory in directoryKeys, do
\n\n
\n- \n
\nIf packagePath starts with directory, then
\n\n
\n- Let target be the value of exports[directory].
\n- Let subpath be the substring of target starting at the index\nof the length of directory.
\n- Return PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, target,\nsubpath).
\n- Throw a Module Not Found error.
\n
PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, target, subpath)
\n\n\n\n
\n- \n
\nIf target is a String, then
\n\n
\n- If target does not start with \"./\", throw a Module Not Found\nerror.
\n- If subpath has non-zero length and target does not end with \"/\",\nthrow a Module Not Found error.
\n- If target or subpath contain any \"node_modules\" segments including\n\"node_modules\" percent-encoding, throw a Module Not Found error.
\n- Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
\n- \n
\nIf resolvedTarget is contained in packageURL, then
\n\n
\n- Let resolved be the URL resolution of the concatenation of\nsubpath and resolvedTarget.
\n- \n
\nIf resolved is contained in resolvedTarget, then
\n\n
\n- Return resolved.
\n- \n
\nOtherwise, if target is an Array, then
\n\n
\n- \n
\nFor each item targetValue in target, do
\n\n
\n- If targetValue is not a String, continue the loop.
\n- Let resolved be the result of\nPACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, targetValue,\nsubpath), continuing the loop on abrupt completion.
\n- Assert: resolved is a String.
\n- Return resolved.
\n- Throw a Module Not Found error.
\n
ESM_FORMAT(url, isMain)
\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 isMain is true or url ends in \".js\", then
\n\n
\n- Return \"module\".
\n- Throw an Unsupported File Extension error.
\n- \n
\nOtherwise,
\n\n
\n- \n
\nIf isMain is true or url ends in \".js\", \".json\" or\n\".node\", then
\n\n
\n- Return \"commonjs\".
\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- 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- Set scopeURL to the parent URL of scopeURL.
\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 --es-module-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 --experimental-modules index.mjs\nsuccess!\n$ node --experimental-modules index #Failure!\nError: Cannot find module\n$ node --experimental-modules --es-module-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.