{ "type": "module", "source": "doc/api/esm.md", "introduced_in": "v8.5.0", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": [ "REPLACEME" ], "pr-url": "https://github.com/nodejs/node/pull/42623", "description": "Add support for chaining loaders." }, { "version": [ "v17.1.0", "v16.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/40250", "description": "Add support for import assertions." }, { "version": [ "v17.0.0", "v16.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/37468", "description": "Consolidate loader 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[, parent])`",
"type": "method",
"name": "resolve",
"signatures": [
{
"params": []
}
],
"desc": "\n\n\nStability: 1 - Experimental
\n
This feature is only available with the --experimental-import-meta-resolve
\ncommand flag enabled.
specifier
<string> The module specifier to resolve relative to parent
.parent
<string> | <URL> The absolute parent module URL to resolve from. If none\nis specified, the value of import.meta.url
is used as the default.Provides a module-relative resolution function scoped to each module, returning\nthe URL string.
\n\nconst dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n
\nimport.meta.resolve
also accepts a second argument which is the parent module\nfrom which to resolve from:
await import.meta.resolve('./dep', import.meta.url);\n
\nThis function is asynchronous because the ES module resolver in Node.js is\nallowed to be asynchronous.
" } ] } ], "miscs": [ { "textRaw": "Modules: ECMAScript modules", "name": "Modules: ECMAScript modules", "introduced_in": "v8.5.0", "type": "misc", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": [ "REPLACEME" ], "pr-url": "https://github.com/nodejs/node/pull/42623", "description": "Add support for chaining loaders." }, { "version": [ "v17.1.0", "v16.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/40250", "description": "Add support for import assertions." }, { "version": [ "v17.0.0", "v16.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/37468", "description": "Consolidate loader 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", "miscs": [ { "textRaw": "Introduction", "name": "esm", "desc": "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\nvia the .mjs
file extension, the package.json
\"type\"
field, or the\n--input-type
flag. Outside of those cases, Node.js will use the CommonJS\nmodule loader. See Determining module system for 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. 'path'
in import { sep } from 'node:path'
. Specifiers are also used in\nexport from
statements, and as the argument to an import()
expression.
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 resolution\nalgorithm. All 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!\"' assert { 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
",
"type": "module",
"displayName": "`node:` imports"
}
],
"type": "module",
"displayName": "URLs"
}
],
"type": "misc",
"displayName": "`import` Specifiers"
},
{
"textRaw": "Import assertions",
"name": "import_assertions",
"meta": {
"added": [
"v17.1.0",
"v16.14.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"desc": "The Import Assertions proposal adds an inline syntax for module import\nstatements to pass on more information alongside the module specifier.
\nimport fooData from './foo.json' assert { type: 'json' };\n\nconst { default: barData } =\n await import('./bar.json', { assert: { type: 'json' } });\n
\nNode.js supports the following type
values, for which the assertion is\nmandatory:
Assertion 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
.
Native modules 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 a flagged experimental\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
. The expectation is that loader\nhooks can provide this workflow in the future.
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' assert { type: 'json' };\n
\nThe assert { type: 'json' }
syntax is mandatory; see Import Assertions.
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", "meta": { "added": [ "v8.8.0" ], "changes": [ { "version": [ "REPLACEME" ], "pr-url": "https://github.com/nodejs/node/pull/42623", "description": "Add support for chaining loaders." }, { "version": "v16.12.0", "pr-url": "https://github.com/nodejs/node/pull/37468", "description": "Removed `getFormat`, `getSource`, `transformSource`, and `globalPreload`; added `load` hook and `getGlobalPreload` hook." } ] }, "stability": 1, "stabilityText": "Experimental", "type": "misc", "desc": "
\n\nThis API is currently being redesigned and will still change.
\n
To 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 apply to the entry point and all import
calls. They\nwon't apply to require
calls; those still follow CommonJS rules.
Loaders follow the pattern of --require
:
node \\\n --experimental-loader unpkg \\\n --experimental-loader http-to-https \\\n --experimental-loader cache-buster\n
\nThese are called in the following sequence: cache-buster
calls\nhttp-to-https
which calls unpkg
.
Hooks are part of a chain, even if that chain consists of only one custom\n(user-provided) hook and the default hook, which is always present. Hook\nfunctions nest: each one must always return a plain object, and chaining happens\nas a result of each function calling next<hookName>()
, which is a reference\nto the subsequent loader's hook.
A hook that returns a value lacking a required property triggers an exception.\nA hook that returns without calling next<hookName>()
and without returning\nshortCircuit: true
also triggers an exception. These errors are to help\nprevent unintentional breaks in the chain.
\n\nThe 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>\nconditions
<string[]> Export conditions of the relevant package.json
importAssertions
<Object>parentURL
<string> | <undefined> The module importing this one, or undefined\nif this is the Node.js entry pointnextResolve
<Function> The subsequent resolve
hook in the chain, or the\nNode.js default resolve
hook after the last user-supplied resolve
hook\n\nformat
<string> | <null> | <undefined> A hint to the load hook (it might be\nignored)\n'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'
shortCircuit
<undefined> | <boolean> A signal that this hook intends to\nterminate the chain of resolve
hooks. Default: false
url
<string> The absolute URL to which this input resolvesThe resolve
hook chain is responsible for resolving file URL for a given\nmodule specifier and parent URL, and optionally its format (such as 'module'
)\nas a hint to the load
hook. If a format is specified, the load
hook is\nultimately responsible for providing the final format
value (and it is free to\nignore the hint provided by resolve
); if resolve
provides a format
, a\ncustom load
hook is required even if only to pass the value to the Node.js\ndefault load
hook.
The module specifier is the string in an import
statement or\nimport()
expression.
The parent URL is the URL of the module that imported this one, or undefined
\nif this is the main entry point for the application.
The conditions
property in context
is an array of conditions for\npackage exports conditions that apply to this resolution\nrequest. They can be used for looking up conditional mappings elsewhere or to\nmodify the list when calling the default resolution logic.
The current package exports conditions are always 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.
export async function resolve(specifier, context, nextResolve) {\n const { parentURL = null } = context;\n\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 shortCircuit: true,\n url: parentURL ?\n new URL(specifier, parentURL).href :\n new URL(specifier).href,\n };\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 nextResolve(specifier, {\n ...context,\n conditions: [...context.conditions, 'another-condition'],\n });\n }\n\n // Defer to the next hook in the chain, which would be the\n // Node.js default resolve if this is the last user-specified loader.\n return nextResolve(specifier, context);\n}\n
"
},
{
"textRaw": "`load(url, context, nextLoad)`",
"type": "method",
"name": "load",
"meta": {
"changes": [
{
"version": "REPLACEME",
"pr-url": "https://github.com/nodejs/node/pull/42623",
"description": "Add support for chaining load hooks. Each hook must either call `nextLoad()` or include a `shortCircuit` property set to `true` in its return."
}
]
},
"signatures": [
{
"params": []
}
],
"desc": "\n\nThe loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
\n\nIn a previous version of this API, this was split across 3 separate, now\ndeprecated, hooks (
\ngetFormat
,getSource
, andtransformSource
).
url
<string> The URL returned by the resolve
chaincontext
<Object>\nconditions
<string[]> Export conditions of the relevant package.json
format
<string> | <null> | <undefined> The format optionally supplied by the\nresolve
hook chainimportAssertions
<Object>nextLoad
<Function> The subsequent load
hook in the chain, or the\nNode.js default load
hook after the last user-supplied load
hook\n\nformat
<string>shortCircuit
<undefined> | <boolean> A signal that this hook intends to\nterminate the chain of resolve
hooks. Default: false
source
<string> | <ArrayBuffer> | <TypedArray> The source for Node.js to evaluateThe load
hook provides a way to define a custom method of determining how\na URL should be interpreted, retrieved, and parsed. It is also in charge of\nvalidating the import assertion.
The final value of format
must be one of the following:
format | \nDescription | \nAcceptable types for source returned by load | \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
The value of source
is ignored for type 'builtin'
because currently it is\nnot possible to replace the value of a Node.js builtin (core) module. The value\nof source
is ignored for type 'commonjs'
because the CommonJS module loader\ndoes not provide a mechanism for the ES module loader to override the\nCommonJS module return value. This limitation might be\novercome in the future.
\n\nCaveat: The ESM
\nload
hook and namespaced exports from CommonJS modules\nare incompatible. Attempting to use them together will result in an empty\nobject from the import. This may be addressed in the future.
\n\nThese types all correspond to classes defined in ECMAScript.
\n
ArrayBuffer
object is a SharedArrayBuffer
.TypedArray
object is a Uint8Array
.If the source value of a text-based format (i.e., 'json'
, 'module'
)\nis not a string, it is converted to a string using util.TextDecoder
.
The load
hook provides a way to define a custom method for retrieving the\nsource code of an ES module specifier. This would allow a loader to potentially\navoid reading files from disk. It could also be used to map an unrecognized\nformat to a supported one, for example yaml
to module
.
export async function load(url, context, nextLoad) {\n const { format } = context;\n\n if (Math.random() > 0.5) { // Some condition\n /*\n For some or all URLs, do some custom logic for retrieving the source.\n Always return an object of the form {\n format: <string>,\n source: <string|buffer>,\n }.\n */\n return {\n format,\n shortCircuit: true,\n source: '...',\n };\n }\n\n // Defer to the next hook in the chain.\n return nextLoad(url, context);\n}\n
\nIn a more advanced scenario, this can also be used to transform an unsupported\nsource to a supported one (see Examples below).
" }, { "textRaw": "`globalPreload()`", "type": "method", "name": "globalPreload", "meta": { "changes": [ { "version": "REPLACEME", "pr-url": "https://github.com/nodejs/node/pull/42623", "description": "Add support for chaining globalPreload hooks." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\nThe loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
\n\nIn a previous version of this API, this hook was named\n
\ngetGlobalPreloadCode
.
context
<Object> Information to assist the preload code\nport
<MessagePort>Sometimes it might be necessary to run some code inside of the same global\nscope that the application runs in. This hook allows the return of a string\nthat is run as a 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 has to construct\nits own require
using module.createRequire()
.
export function globalPreload(context) {\n return `\\\nglobalThis.someInjectedProperty = 42;\nconsole.log('I just set some globals!');\n\nconst { createRequire } = getBuiltin('module');\nconst { cwd } = getBuiltin('process');\n\nconst require = createRequire(cwd() + '/<preload>');\n// [...]\n`;\n}\n
\nIn order to allow communication between the application and the loader, another\nargument is provided to the preload code: port
. This is available as a\nparameter to the loader hook and inside of the source text returned by the hook.\nSome care must be taken in order to properly call port.ref()
and\nport.unref()
to prevent a process from being in a state where it won't\nclose normally.
/**\n * This example has the application context send a message to the loader\n * and sends the message back to the application context\n */\nexport function globalPreload({ port }) {\n port.onmessage = (evt) => {\n port.postMessage(evt.data);\n };\n return `\\\n port.postMessage('console.log(\"I went to the Loader and back\");');\n port.onmessage = (evt) => {\n eval(evt.data);\n };\n `;\n}\n
\nThe various loader hooks can be used together to accomplish wide-ranging\ncustomizations of the Node.js code loading and evaluation behaviors.
" } ], "modules": [ { "textRaw": "HTTPS loader", "name": "https_loader", "desc": "In current Node.js, specifiers starting with https://
are experimental (see\nHTTPS and HTTP imports).
The loader below registers hooks to enable rudimentary support for such\nspecifiers. While 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.
\n// https-loader.mjs\nimport { get } from 'node:https';\n\nexport function resolve(specifier, context, nextResolve) {\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 shortCircuit: true,\n url: specifier\n };\n } else if (parentURL && parentURL.startsWith('https://')) {\n return {\n shortCircuit: true,\n url: new URL(specifier, parentURL).href,\n };\n }\n\n // Let Node.js handle all other specifiers.\n return nextResolve(specifier, context);\n}\n\nexport function load(url, context, nextLoad) {\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({\n // This example assumes all network-provided JavaScript is ES module\n // code.\n format: 'module',\n shortCircuit: true,\n source: data,\n }));\n }).on('error', (err) => reject(err));\n });\n }\n\n // Let Node.js handle all other URLs.\n return nextLoad(url, context);\n}\n
\n// main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n
\nWith the preceding loader, running\nnode --experimental-loader ./https-loader.mjs ./main.mjs
\nprints 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 load
hook. Before that hook gets called,\nhowever, a resolve
hook needs to tell Node.js not to\nthrow an error on unknown file types.
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 { readFile } from 'node:fs/promises';\nimport { dirname, extname, resolve as resolvePath } from 'node:path';\nimport { cwd } from 'node:process';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport CoffeeScript from 'coffeescript';\n\nconst baseURL = pathToFileURL(`${cwd()}/`).href;\n\n// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.\nconst extensionsRegex = /\\.coffee$|\\.litcoffee$|\\.coffee\\.md$/;\n\nexport async function resolve(specifier, context, nextResolve) {\n if (extensionsRegex.test(specifier)) {\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 return {\n shortCircuit: true,\n url: new URL(specifier, parentURL).href\n };\n }\n\n // Let Node.js handle all other specifiers.\n return nextResolve(specifier, context);\n}\n\nexport async function load(url, context, nextLoad) {\n if (extensionsRegex.test(url)) {\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. Because\n // CoffeeScript transpiles into JavaScript, it should be one of the two\n // JavaScript formats: 'commonjs' or 'module'.\n\n // CoffeeScript files can be either CommonJS or ES modules, so we want any\n // CoffeeScript file to be treated by Node.js the same as a .js file at the\n // same location. To determine how Node.js would interpret an arbitrary .js\n // file, search up the file system for the nearest parent package.json file\n // and read its \"type\" field.\n const format = await getPackageType(url);\n // When a hook returns a format of 'commonjs', `source` is be ignored.\n // To handle CommonJS files, a handler needs to be registered with\n // `require.extensions` in order to process the files with the CommonJS\n // loader. Avoiding the need for a separate CommonJS handler is a future\n // enhancement planned for ES module loaders.\n if (format === 'commonjs') {\n return {\n format,\n shortCircuit: true,\n };\n }\n\n const { source: rawSource } = await nextLoad(url, { ...context, format });\n // This hook converts CoffeeScript source code into JavaScript source code\n // for all imported CoffeeScript files.\n const transformedSource = coffeeCompile(rawSource.toString(), url);\n\n return {\n format,\n shortCircuit: true,\n source: transformedSource,\n };\n }\n\n // Let Node.js handle all other URLs.\n return nextLoad(url, context);\n}\n\nasync function getPackageType(url) {\n // `url` is only a file path during the first iteration when passed the\n // resolved url from the load() hook\n // an actual file path from load() will contain a file extension as it's\n // required by the spec\n // this simple truthy check for whether `url` contains a file extension will\n // work for most projects but does not cover some edge-cases (such as\n // extensionless files or a url ending in a trailing space)\n const isFilePath = !!extname(url);\n // If it is a file path, get the directory it's in\n const dir = isFilePath ?\n dirname(fileURLToPath(url)) :\n url;\n // Compose a file path to a package.json in the same directory,\n // which may or may not exist\n const packagePath = resolvePath(dir, 'package.json');\n // Try to read the possibly nonexistent package.json\n const type = await readFile(packagePath, { encoding: 'utf8' })\n .then((filestring) => JSON.parse(filestring).type)\n .catch((err) => {\n if (err?.code !== 'ENOENT') console.error(err);\n });\n // Ff package.json existed and contained a `type` field with a value, voila\n if (type) return type;\n // Otherwise, (if not at the root) continue checking the next directory up\n // If at the root, stop and return false\n return dir.length > 1 && getPackageType(resolvePath(dir, '..'));\n}\n
\n# main.coffee\nimport { scream } from './scream.coffee'\nconsole.log scream 'hello, world'\n\nimport { version } from 'node:process'\nconsole.log \"Brought to you by Node.js version #{version}\"\n
\n# scream.coffee\nexport scream = (str) -> str.toUpperCase()\n
\nWith the preceding loader, running\nnode --experimental-loader ./coffeescript-loader.mjs main.coffee
\ncauses 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- 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- Load resolved as module format, format.
\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, \"\", false, false,\nconditions).
\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, \"\", false, 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 subpath 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, subpath, true, 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, subpath, pattern,\ninternal, conditions)
\n\n\n\n
\n- If target is a String, then\n
\n\n
\n- If pattern is false, subpath has non-zero length and target\ndoes not end with \"/\", throw an Invalid Module Specifier error.
\n- If target does not start with \"./\", then\n
\n\n
\n- If internal is true and target does not start with \"../\" or\n\"/\" and is not a valid URL, then\n
\n\n
\n- If pattern is true, then\n
\n\n
\n- Return PACKAGE_RESOLVE(target with every instance of\n\"*\" replaced by subpath, packageURL + \"/\").
\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, case insensitive and\nincluding percent encoded variants, throw an Invalid Package Target\nerror.
\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, case insensitive and including percent\nencoded variants, throw an Invalid Module Specifier error.
\n- If pattern is true, then\n
\n\n
\n- Return the URL resolution of resolvedTarget with every instance of\n\"*\" replaced with subpath.
\n- Otherwise,\n
\n\n
\n- Return the URL resolution of the concatenation of subpath and\nresolvedTarget.
\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, subpath, pattern, internal,\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, subpath, pattern, internal,\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\", then\n
\n\n
\n- Return \"module\".
\n- Throw an Unsupported File Extension error.
\n- Otherwise,\n
\n\n
\n- Throw an Unsupported File Extension error.
\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": "Resolver 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\nLoaders API has advanced to the point that equivalent functionality can\nbe achieved via custom loaders.
\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 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[, parent])`",
"type": "method",
"name": "resolve",
"signatures": [
{
"params": []
}
],
"desc": "\n\n\nStability: 1 - Experimental
\n
This feature is only available with the --experimental-import-meta-resolve
\ncommand flag enabled.
specifier
<string> The module specifier to resolve relative to parent
.parent
<string> | <URL> The absolute parent module URL to resolve from. If none\nis specified, the value of import.meta.url
is used as the default.Provides a module-relative resolution function scoped to each module, returning\nthe URL string.
\n\nconst dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n
\nimport.meta.resolve
also accepts a second argument which is the parent module\nfrom which to resolve from:
await import.meta.resolve('./dep', import.meta.url);\n
\nThis function is asynchronous because the ES module resolver in Node.js is\nallowed to be asynchronous.
" } ] } ] } ] }