{ "type": "module", "source": "doc/api/esm.md", "introduced_in": "v8.5.0", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": [ "v15.3.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.

", "properties": [ { "textRaw": "`url` {string} The absolute `file:` URL of the module.", "type": "string", "name": "url", "desc": "

This is defined exactly the same as it is in browsers providing the URL of the\ncurrent module file.

\n

This enables useful patterns such as relative file loading:

\n
import { readFileSync } from '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

Stability: 1 - Experimental

\n
\n

This feature is only available with the --experimental-import-meta-resolve\ncommand flag enabled.

\n\n

Provides a module-relative resolution function scoped to each module, returning\nthe URL string.

\n\n
const dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n
\n

import.meta.resolve also accepts a second argument which is the parent module\nfrom which to resolve from:

\n\n
await import.meta.resolve('./dep', import.meta.url);\n
\n

This 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": [ "v15.3.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.

\n

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
\n

The following example of an ES module imports the function from addTwo.mjs:

\n
// app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));\n
\n

Node.js fully supports ECMAScript modules as they are currently specified and\nprovides interoperability between them and its original module format,\nCommonJS.

\n\n

\n\n

", "type": "misc", "displayName": "esm" }, { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "

Node.js treats JavaScript code as CommonJS modules by default.\nAuthors can tell Node.js to treat JavaScript code as ECMAScript modules\nvia the .mjs file extension, the package.json \"type\" field, or the\n--input-type flag. See\nModules: Packages for more\ndetails.

\n\n

\n\n\n\n\n\n\n\n\n\n\n\n\n

" }, { "textRaw": "Packages", "name": "packages", "desc": "

This section was moved to Modules: Packages.

", "type": "misc", "displayName": "Packages" }, { "textRaw": "`import` Specifiers", "name": "`import`_specifiers", "modules": [ { "textRaw": "Terminology", "name": "terminology", "desc": "

The specifier of an import statement is the string after the from keyword,\ne.g. 'path' in import { sep } from 'path'. Specifiers are also used in\nexport from statements, and as the argument to an import() expression.

\n

There are three types of specifiers:

\n\n

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.

\n

Like 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\".

\n

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.

\n

This behavior matches how import behaves in browser environments, assuming a\ntypically configured server.

", "type": "module", "displayName": "Mandatory file extensions" }, { "textRaw": "URLs", "name": "urls", "desc": "

ES modules are resolved and cached as URLs. This means that files containing\nspecial characters such as # and ? need to be escaped.

\n

file:, node:, and data: URL schemes are supported. A specifier like\n'https://example.com/app.js' is not supported natively in Node.js unless using\na custom HTTPS loader.

", "modules": [ { "textRaw": "`file:` URLs", "name": "`file:`_urls", "desc": "

Modules are loaded multiple times if the import specifier used to resolve\nthem has a different query or fragment.

\n
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
\n

The 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.

", "type": "module", "displayName": "`file:` URLs" }, { "textRaw": "`data:` Imports", "name": "`data:`_imports", "meta": { "added": [ "v12.10.0" ], "changes": [] }, "desc": "

data: URLs are supported for importing with the following MIME types:

\n\n

data: 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. An example of a data:\nURLs being used is:

\n
import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"';\n
", "type": "module", "displayName": "`data:` Imports" }, { "textRaw": "`node:` Imports", "name": "`node:`_imports", "meta": { "added": [ "v14.13.1", "v12.20.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37246", "description": "Added `node:` import support to `require(...)`." } ] }, "desc": "

node: URLs are supported as an alternative means to load Node.js builtin\nmodules. This URL scheme allows for builtin modules to be referenced by valid\nabsolute URL strings.

\n
import fs from 'node:fs/promises';\n
", "type": "module", "displayName": "`node:` Imports" } ], "type": "module", "displayName": "URLs" } ], "type": "misc", "displayName": "`import` Specifiers" }, { "textRaw": "Builtin modules", "name": "builtin_modules", "desc": "

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().

\n
import EventEmitter from 'events';\nconst e = new EventEmitter();\n
\n
import { readFile } from 'fs';\nreadFile('./foo.txt', (err, source) => {\n  if (err) {\n    console.error(err);\n  } else {\n    console.log(source);\n  }\n});\n
\n
import fs, { readFileSync } from 'fs';\nimport { syncBuiltinESMExports } from 'module';\nimport { Buffer } from '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.

", "type": "misc", "displayName": "`import()` expressions" }, { "textRaw": "Interoperability with CommonJS", "name": "interoperability_with_commonjs", "modules": [ { "textRaw": "`import` statements", "name": "`import`_statements", "desc": "

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.

\n

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.

", "type": "module", "displayName": "`import` statements" }, { "textRaw": "`require`", "name": "`require`", "desc": "

The CommonJS module require always treats the files it references as CommonJS.

\n

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.

", "type": "module", "displayName": "`require`" }, { "textRaw": "CommonJS Namespaces", "name": "commonjs_namespaces", "desc": "

CommonJS modules consist of a module.exports object which can be of any type.

\n

When importing a CommonJS module, it can be reliably imported using the ES\nmodule default import or its corresponding sugar syntax:

\n\n
import { 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
\n

The ECMAScript Module Namespace representation of a CommonJS module is always\na namespace with a default export key pointing to the CommonJS\nmodule.exports value.

\n

This Module Namespace Exotic Object can be directly observed either when using\nimport * as m from 'cjs' or a dynamic import:

\n\n
import * as m from 'cjs';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n//   [Module] { default: <module.exports> }\n//   true\n
\n

For better compatibility with existing usage in the JS ecosystem, Node.js\nin addition attempts to determine the CommonJS named exports of every imported\nCommonJS module to provide them as separate ES module exports using a static\nanalysis process.

\n

For example, consider a CommonJS module written:

\n
// cjs.cjs\nexports.name = 'exported';\n
\n

The preceding module supports named imports in ES modules:

\n\n
import { name } from './cjs.cjs';\nconsole.log(name);\n// Prints: 'exported'\n\nimport cjs from './cjs.cjs';\nconsole.log(cjs);\n// Prints: { name: 'exported' }\n\nimport * as m from './cjs.cjs';\nconsole.log(m);\n// Prints: [Module] { default: { name: 'exported' }, name: 'exported' }\n
\n

As can be seen from the last example of the Module Namespace Exotic Object being\nlogged, the name export is copied off of the module.exports object and set\ndirectly on the ES module namespace when the module is imported.

\n

Live binding updates or new exports added to module.exports are not detected\nfor these named exports.

\n

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.

\n

Named 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.

\n

If needed, a require function can be constructed within an ES module using\nmodule.createRequire().

", "type": "module", "displayName": "No `require`, `exports` or `module.exports`" }, { "textRaw": "No `__filename` or `__dirname`", "name": "no_`__filename`_or_`__dirname`", "desc": "

These CommonJS variables are not available in ES modules.

\n

__filename and __dirname use cases can be replicated via\nimport.meta.url.

", "type": "module", "displayName": "No `__filename` or `__dirname`" }, { "textRaw": "No JSON Module Loading", "name": "no_json_module_loading", "desc": "

JSON imports are still experimental and only supported via the\n--experimental-json-modules flag.

\n

Local JSON files can be loaded relative to import.meta.url with fs directly:

\n\n
import { readFile } from 'fs/promises';\nconst json = JSON.parse(await readFile(new URL('./dat.json', import.meta.url)));\n
\n

Alternatively module.createRequire() can be used.

", "type": "module", "displayName": "No JSON Module Loading" }, { "textRaw": "No Native Module Loading", "name": "no_native_module_loading", "desc": "

Native modules are not currently supported with ES module imports.

\n

They can instead be loaded with module.createRequire() or\nprocess.dlopen.

", "type": "module", "displayName": "No Native Module Loading" }, { "textRaw": "No `require.resolve`", "name": "no_`require.resolve`", "desc": "

Relative resolution can be handled via new URL('./local', import.meta.url).

\n

For a complete require.resolve replacement, there is a flagged experimental\nimport.meta.resolve API.

\n

Alternatively module.createRequire() can be used.

", "type": "module", "displayName": "No `require.resolve`" }, { "textRaw": "No `NODE_PATH`", "name": "no_`node_path`", "desc": "

NODE_PATH is not part of resolving import specifiers. Please use symlinks\nif this behavior is desired.

", "type": "module", "displayName": "No `NODE_PATH`" }, { "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.

", "type": "module", "displayName": "No `require.extensions`" }, { "textRaw": "No `require.cache`", "name": "no_`require.cache`", "desc": "

require.cache is not used by import as the ES module loader has its own\nseparate cache.

\n

", "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": "

Currently importing JSON modules are only supported in the commonjs mode\nand are loaded using the CJS loader. WHATWG JSON modules specification are\nstill being standardized, and are experimentally supported by including the\nadditional flag --experimental-json-modules when running Node.js.

\n

When the --experimental-json-modules flag is included, both the\ncommonjs and module mode use the new experimental JSON\nloader. The imported JSON only exposes a default. There is no\nsupport for named exports. A cache entry is created in the CommonJS\ncache to avoid duplication. The same object is returned in\nCommonJS if the JSON module has already been imported from the\nsame path.

\n

Assuming an index.mjs with

\n\n
import packageConfig from './package.json';\n
\n

The --experimental-json-modules flag is needed for the module\nto work.

\n
node index.mjs # fails\nnode --experimental-json-modules index.mjs # works\n
\n

", "type": "misc", "displayName": "JSON modules" }, { "textRaw": "Wasm modules", "name": "wasm_modules", "stability": 1, "stabilityText": "Experimental", "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.

\n

This integration is in line with the\nES Module Integration Proposal for Web Assembly.

\n

For example, an index.mjs containing:

\n
import * as M from './module.wasm';\nconsole.log(M);\n
\n

executed under:

\n
node --experimental-wasm-modules index.mjs\n
\n

would provide the exports interface for the instantiation of module.wasm.

\n

", "type": "misc", "displayName": "Wasm modules" }, { "textRaw": "Top-level `await`", "name": "top-level_`await`", "stability": 1, "stabilityText": "Experimental", "desc": "

The await keyword may be used in the top level (outside of async functions)\nwithin modules as per the ECMAScript Top-Level await proposal.

\n

Assuming an a.mjs with

\n\n
export const five = await Promise.resolve(5);\n
\n

And a b.mjs with

\n
import { five } from './a.mjs';\n\nconsole.log(five); // Logs `5`\n
\n
node b.mjs # works\n
\n

", "type": "misc", "displayName": "Top-level `await`" }, { "textRaw": "Loaders", "name": "Loaders", "stability": 1, "stabilityText": "Experimental", "type": "misc", "desc": "

Note: This 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.

\n

When hooks are used they only apply to ES module loading and not to any\nCommonJS modules loaded.

", "miscs": [ { "textRaw": "Hooks", "name": "hooks", "methods": [ { "textRaw": "`resolve(specifier, context, defaultResolve)`", "type": "method", "name": "resolve", "signatures": [ { "params": [] } ], "desc": "
\n

Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

\n
\n\n

The resolve hook returns the resolved file URL for a given module specifier\nand parent URL. The module specifier is the string in an import statement or\nimport() expression, and the parent URL is the URL of the module that imported\nthis one, or undefined if this is the main entry point for the application.

\n

The conditions property on the context is an array of conditions for\nConditional exports that apply to this resolution request. They can be used\nfor looking up conditional mappings elsewhere or to modify the list when calling\nthe default resolution logic.

\n

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.

\n
/**\n * @param {string} specifier\n * @param {{\n *   conditions: !Array<string>,\n *   parentURL: !(string | undefined),\n * }} context\n * @param {Function} defaultResolve\n * @returns {Promise<{ url: string }>}\n */\nexport async function resolve(specifier, context, defaultResolve) {\n  const { parentURL = null } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all specifiers, do some custom logic for resolving.\n    // Always return an object of the form {url: <string>}.\n    return {\n      url: parentURL ?\n        new URL(specifier, parentURL).href :\n        new URL(specifier).href,\n    };\n  }\n  if (Math.random() < 0.5) { // Another condition.\n    // When calling `defaultResolve`, the arguments can be modified. In this\n    // case it's adding another value for matching conditional exports.\n    return defaultResolve(specifier, {\n      ...context,\n      conditions: [...context.conditions, 'another-condition'],\n    });\n  }\n  // Defer to Node.js for all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n
" }, { "textRaw": "`getFormat(url, context, defaultGetFormat)`", "type": "method", "name": "getFormat", "signatures": [ { "params": [] } ], "desc": "
\n

Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

\n
\n\n

The getFormat hook provides a way to define a custom method of determining how\na URL should be interpreted. The format returned also affects what the\nacceptable forms of source values are for a module when parsing. This can be one\nof the following:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
formatDescriptionAcceptable Types For source Returned by getSource or transformSource
'builtin'Load a Node.js builtin moduleNot applicable
'commonjs'Load a Node.js CommonJS moduleNot applicable
'json'Load a JSON file{ string, ArrayBuffer, TypedArray }
'module'Load an ES module{ string, ArrayBuffer, TypedArray }
'wasm'Load a WebAssembly module{ ArrayBuffer, TypedArray }
\n

Note: These types all correspond to classes defined in ECMAScript.

\n\n

Note: If the source value of a text-based format (i.e., 'json', 'module') is\nnot a string, it is converted to a string using util.TextDecoder.

\n
/**\n * @param {string} url\n * @param {Object} context (currently empty)\n * @param {Function} defaultGetFormat\n * @returns {Promise<{ format: string }>}\n */\nexport async function getFormat(url, context, defaultGetFormat) {\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for determining format.\n    // Always return an object of the form {format: <string>}, where the\n    // format is one of the strings in the preceding table.\n    return {\n      format: 'module',\n    };\n  }\n  // Defer to Node.js for all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n
" }, { "textRaw": "`getSource(url, context, defaultGetSource)`", "type": "method", "name": "getSource", "signatures": [ { "params": [] } ], "desc": "
\n

Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

\n
\n\n

The getSource hook provides a way to define a custom method for retrieving\nthe source code of an ES module specifier. This would allow a loader to\npotentially avoid reading files from disk.

\n
/**\n * @param {string} url\n * @param {{ format: string }} context\n * @param {Function} defaultGetSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function getSource(url, context, defaultGetSource) {\n  const { format } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for retrieving the source.\n    // Always return an object of the form {source: <string|buffer>}.\n    return {\n      source: '...',\n    };\n  }\n  // Defer to Node.js for all other URLs.\n  return defaultGetSource(url, context, defaultGetSource);\n}\n
" }, { "textRaw": "`transformSource(source, context, defaultTransformSource)`", "type": "method", "name": "transformSource", "signatures": [ { "params": [] } ], "desc": "
\n

Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

\n
\n\n

The transformSource hook provides a way to modify the source code of a loaded\nES module file after the source string has been loaded but before Node.js has\ndone anything with it.

\n

If this hook is used to convert unknown-to-Node.js file types into executable\nJavaScript, a resolve hook is also necessary in order to register any\nunknown-to-Node.js file extensions. See the transpiler loader example below.

\n
/**\n * @param {!(string | SharedArrayBuffer | Uint8Array)} source\n * @param {{\n *   format: string,\n *   url: string,\n * }} context\n * @param {Function} defaultTransformSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function transformSource(source, context, defaultTransformSource) {\n  const { url, format } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for modifying the source.\n    // Always return an object of the form {source: <string|buffer>}.\n    return {\n      source: '...',\n    };\n  }\n  // Defer to Node.js for all other sources.\n  return defaultTransformSource(source, context, defaultTransformSource);\n}\n
" }, { "textRaw": "`getGlobalPreloadCode()`", "type": "method", "name": "getGlobalPreloadCode", "signatures": [ { "params": [] } ], "desc": "
\n

Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

\n
\n\n

Sometimes it might be necessary to run some code inside of the same global scope\nthat the application runs in. This hook allows the return of a string that is\nrun as sloppy-mode script on startup.

\n

Similar 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).

\n

If the code needs more advanced require features, it has to construct\nits own require using module.createRequire().

\n
/**\n * @returns {string} Code to run before application startup\n */\nexport function getGlobalPreloadCode() {\n  return `\\\nglobalThis.someInjectedProperty = 42;\nconsole.log('I just set some globals!');\n\nconst { createRequire } = getBuiltin('module');\nconst { cwd } = getBuiltin('process');\n\nconst require = createRequire(cwd() + '/<preload>');\n// [...]\n`;\n}\n
\n

Examples

\n

The various loader hooks can be used together to accomplish wide-ranging\ncustomizations of Node.js’ code loading and evaluation behaviors.

" } ], "modules": [ { "textRaw": "HTTPS loader", "name": "https_loader", "desc": "

In current Node.js, specifiers starting with https:// are unsupported. The\nloader below registers hooks to enable rudimentary support for such specifiers.\nWhile this may seem like a significant improvement to Node.js core\nfunctionality, there are substantial downsides to actually using this loader:\nperformance is much slower than loading files from disk, there is no caching,\nand there is no security.

\n
// https-loader.mjs\nimport { get } from 'https';\n\nexport function resolve(specifier, context, defaultResolve) {\n  const { parentURL = null } = context;\n\n  // Normally Node.js would error on specifiers starting with 'https://', so\n  // this hook intercepts them and converts them into absolute URLs to be\n  // passed along to the later hooks below.\n  if (specifier.startsWith('https://')) {\n    return {\n      url: specifier\n    };\n  } else if (parentURL && parentURL.startsWith('https://')) {\n    return {\n      url: new URL(specifier, parentURL).href\n    };\n  }\n\n  // Let Node.js handle all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n  // This loader assumes all network-provided JavaScript is ES module code.\n  if (url.startsWith('https://')) {\n    return {\n      format: 'module'\n    };\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function getSource(url, context, defaultGetSource) {\n  // For JavaScript to be loaded over the network, we need to fetch and\n  // return it.\n  if (url.startsWith('https://')) {\n    return new Promise((resolve, reject) => {\n      get(url, (res) => {\n        let data = '';\n        res.on('data', (chunk) => data += chunk);\n        res.on('end', () => resolve({ source: data }));\n      }).on('error', (err) => reject(err));\n    });\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetSource(url, context, defaultGetSource);\n}\n
\n
// main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n
\n

With 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.

", "type": "module", "displayName": "HTTPS loader" }, { "textRaw": "Transpiler loader", "name": "transpiler_loader", "desc": "

Sources that are in formats Node.js doesn’t understand can be converted into\nJavaScript using the transformSource hook. Before that hook gets called,\nhowever, other hooks need to tell Node.js not to throw an error on unknown file\ntypes; and to tell Node.js how to load this new file type.

\n

This is less performant than transpiling source files before running\nNode.js; a transpiler loader should only be used for development and testing\npurposes.

\n
// coffeescript-loader.mjs\nimport { URL, pathToFileURL } from 'url';\nimport CoffeeScript from 'coffeescript';\nimport { cwd } from 'process';\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 function resolve(specifier, context, defaultResolve) {\n  const { parentURL = baseURL } = context;\n\n  // Node.js normally errors on unknown file extensions, so return a URL for\n  // specifiers ending in the CoffeeScript file extensions.\n  if (extensionsRegex.test(specifier)) {\n    return {\n      url: new URL(specifier, parentURL).href\n    };\n  }\n\n  // Let Node.js handle all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n  // Now that we patched resolve to let CoffeeScript URLs through, we need to\n  // tell Node.js what format such URLs should be interpreted as. For the\n  // purposes of this loader, all CoffeeScript URLs are ES modules.\n  if (extensionsRegex.test(url)) {\n    return {\n      format: 'module'\n    };\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function transformSource(source, context, defaultTransformSource) {\n  const { url, format } = context;\n\n  if (extensionsRegex.test(url)) {\n    return {\n      source: CoffeeScript.compile(source, { bare: true })\n    };\n  }\n\n  // Let Node.js handle all other sources.\n  return defaultTransformSource(source, context, defaultTransformSource);\n}\n
\n
# main.coffee\nimport { scream } from './scream.coffee'\nconsole.log scream 'hello, world'\n\nimport { version } from 'process'\nconsole.log \"Brought to you by Node.js version #{version}\"\n
\n
# scream.coffee\nexport scream = (str) -> str.toUpperCase()\n
\n

With 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.

", "type": "module", "displayName": "Transpiler loader" } ], "type": "misc", "displayName": "Hooks" } ] }, { "textRaw": "Resolution algorithm", "name": "resolution_algorithm", "modules": [ { "textRaw": "Features", "name": "features", "desc": "

The resolver has the following properties:

\n", "type": "module", "displayName": "Features" }, { "textRaw": "Resolver algorithm", "name": "resolver_algorithm", "desc": "

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.

\n

The 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.

\n

In the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.

\n

defaultConditions is the conditional environment name array,\n[\"node\", \"import\"].

\n

The resolver can throw the following errors:

\n", "type": "module", "displayName": "Resolver algorithm" }, { "textRaw": "Resolver Algorithm Specification", "name": "resolver_algorithm_specification", "desc": "

ESM_RESOLVE(specifier, parentURL)

\n
\n
    \n
  1. Let resolved be undefined.
  2. \n
  3. If specifier is a valid URL, then\n
      \n
    1. Set resolved to the result of parsing and reserializing\nspecifier as a URL.
    2. \n
    \n
  4. \n
  5. Otherwise, if specifier starts with \"/\", \"./\" or \"../\", then\n
      \n
    1. Set resolved to the URL resolution of specifier relative to\nparentURL.
    2. \n
    \n
  6. \n
  7. Otherwise, if specifier starts with \"#\", then\n
      \n
    1. Set resolved to the destructured value of the result of\nPACKAGE_IMPORTS_RESOLVE(specifier, parentURL,\ndefaultConditions).
    2. \n
    \n
  8. \n
  9. Otherwise,\n
      \n
    1. Note: specifier is now a bare specifier.
    2. \n
    3. Set resolved the result of\nPACKAGE_RESOLVE(specifier, parentURL).
    4. \n
    \n
  10. \n
  11. If resolved contains any percent encodings of \"/\" or \"\\\" (\"%2f\"\nand \"%5C\" respectively), then\n
      \n
    1. Throw an Invalid Module Specifier error.
    2. \n
    \n
  12. \n
  13. If the file at resolved is a directory, then\n
      \n
    1. Throw an Unsupported Directory Import error.
    2. \n
    \n
  14. \n
  15. If the file at resolved does not exist, then\n
      \n
    1. Throw a Module Not Found error.
    2. \n
    \n
  16. \n
  17. Set resolved to the real path of resolved.
  18. \n
  19. Let format be the result of ESM_FORMAT(resolved).
  20. \n
  21. Load resolved as module format, format.
  22. \n
  23. Return resolved.
  24. \n
\n
\n

PACKAGE_RESOLVE(packageSpecifier, parentURL)

\n
\n
    \n
  1. Let packageName be undefined.
  2. \n
  3. If packageSpecifier is an empty string, then\n
      \n
    1. Throw an Invalid Module Specifier error.
    2. \n
    \n
  4. \n
  5. If packageSpecifier does not start with \"@\", then\n
      \n
    1. Set packageName to the substring of packageSpecifier until the first\n\"/\" separator or the end of the string.
    2. \n
    \n
  6. \n
  7. Otherwise,\n
      \n
    1. If packageSpecifier does not contain a \"/\" separator, then\n
        \n
      1. Throw an Invalid Module Specifier error.
      2. \n
      \n
    2. \n
    3. Set packageName to the substring of packageSpecifier\nuntil the second \"/\" separator or the end of the string.
    4. \n
    \n
  8. \n
  9. If packageName starts with \".\" or contains \"\\\" or \"%\", then\n
      \n
    1. Throw an Invalid Module Specifier error.
    2. \n
    \n
  10. \n
  11. Let packageSubpath be \".\" concatenated with the substring of\npackageSpecifier from the position at the length of packageName.
  12. \n
  13. Let selfUrl be the result of\nPACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
  14. \n
  15. If selfUrl is not undefined, return selfUrl.
  16. \n
  17. If packageSubpath is \".\" and packageName is a Node.js builtin\nmodule, then\n
      \n
    1. Return the string \"node:\" concatenated with packageSpecifier.
    2. \n
    \n
  18. \n
  19. While parentURL is not the file system root,\n
      \n
    1. Let packageURL be the URL resolution of \"node_modules/\"\nconcatenated with packageSpecifier, relative to parentURL.
    2. \n
    3. Set parentURL to the parent folder URL of parentURL.
    4. \n
    5. If the folder at packageURL does not exist, then\n
        \n
      1. Set parentURL to the parent URL path of parentURL.
      2. \n
      3. Continue the next loop iteration.
      4. \n
      \n
    6. \n
    7. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
    8. \n
    9. If pjson is not null and pjson.exports is not null or\nundefined, then\n
        \n
      1. Let exports be pjson.exports.
      2. \n
      3. Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath,\npjson.exports, defaultConditions).
      4. \n
      \n
    10. \n
    11. Otherwise, if packageSubpath is equal to \".\", then\n
        \n
      1. Return the result applying the legacy LOAD_AS_DIRECTORY\nCommonJS resolver to packageURL, throwing a Module Not Found\nerror for no resolution.
      2. \n
      \n
    12. \n
    13. Otherwise,\n
        \n
      1. Return the URL resolution of packageSubpath in packageURL.
      2. \n
      \n
    14. \n
    \n
  20. \n
  21. Throw a Module Not Found error.
  22. \n
\n
\n

PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)

\n
\n
    \n
  1. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
  2. \n
  3. If packageURL is null, then\n
      \n
    1. Return undefined.
    2. \n
    \n
  4. \n
  5. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
  6. \n
  7. If pjson is null or if pjson.exports is null or\nundefined, then\n
      \n
    1. Return undefined.
    2. \n
    \n
  8. \n
  9. If pjson.name is equal to packageName, then\n
      \n
    1. Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, subpath, pjson.exports,\ndefaultConditions).
    2. \n
    \n
  10. \n
  11. Otherwise, return undefined.
  12. \n
\n
\n

PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)

\n
\n
    \n
  1. If exports is an Object with both a key starting with \".\" and a key not\nstarting with \".\", throw an Invalid Package Configuration error.
  2. \n
  3. If subpath is equal to \".\", then\n
      \n
    1. Let mainExport be undefined.
    2. \n
    3. If exports is a String or Array, or an Object containing no keys\nstarting with \".\", then\n
        \n
      1. Set mainExport to exports.
      2. \n
      \n
    4. \n
    5. Otherwise if exports is an Object containing a \".\" property, then\n
        \n
      1. Set mainExport to exports[\".\"].
      2. \n
      \n
    6. \n
    7. If mainExport is not undefined, then\n
        \n
      1. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, \"\", false, false,\nconditions).
      2. \n
      3. If resolved is not null or undefined, then\n
          \n
        1. Return resolved.
        2. \n
        \n
      4. \n
      \n
    8. \n
    \n
  4. \n
  5. Otherwise, if exports is an Object and all keys of exports start with\n\".\", then\n
      \n
    1. Let matchKey be the string \"./\" concatenated with subpath.
    2. \n
    3. Let resolvedMatch be result of PACKAGE_IMPORTS_EXPORTS_RESOLVE(\nmatchKey, exports, packageURL, false, conditions).
    4. \n
    5. If resolvedMatch.resolve is not null or undefined, then\n
        \n
      1. Return resolvedMatch.
      2. \n
      \n
    6. \n
    \n
  6. \n
  7. Throw a Package Path Not Exported error.
  8. \n
\n
\n

PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)

\n
\n
    \n
  1. Assert: specifier begins with \"#\".
  2. \n
  3. If specifier is exactly equal to \"#\" or starts with \"#/\", then\n
      \n
    1. Throw an Invalid Module Specifier error.
    2. \n
    \n
  4. \n
  5. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
  6. \n
  7. If packageURL is not null, then\n
      \n
    1. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
    2. \n
    3. If pjson.imports is a non-null Object, then\n
        \n
      1. Let resolvedMatch be the result of\nPACKAGE_IMPORTS_EXPORTS_RESOLVE(specifier, pjson.imports,\npackageURL, true, conditions).
      2. \n
      3. If resolvedMatch.resolve is not null or undefined, then\n
          \n
        1. Return resolvedMatch.
        2. \n
        \n
      4. \n
      \n
    4. \n
    \n
  8. \n
  9. Throw a Package Import Not Defined error.
  10. \n
\n
\n

PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL,\nisImports, conditions)

\n
\n
    \n
  1. If matchKey is a key of matchObj, and does not end in \"*\", then\n
      \n
    1. Let target be the value of matchObj[matchKey].
    2. \n
    3. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, \"\", false, isImports, conditions).
    4. \n
    5. Return the object { resolved, exact: true }.
    6. \n
    \n
  2. \n
  3. Let expansionKeys be the list of keys of matchObj ending in \"/\"\nor \"*\", sorted by length descending.
  4. \n
  5. For each key expansionKey in expansionKeys, do\n
      \n
    1. If expansionKey ends in \"*\" and matchKey starts with but is\nnot equal to the substring of expansionKey excluding the last \"*\"\ncharacter, then\n
        \n
      1. Let target be the value of matchObj[expansionKey].
      2. \n
      3. Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey minus one.
      4. \n
      5. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, true, isImports,\nconditions).
      6. \n
      7. Return the object { resolved, exact: true }.
      8. \n
      \n
    2. \n
    3. If matchKey starts with expansionKey, then\n
        \n
      1. Let target be the value of matchObj[expansionKey].
      2. \n
      3. Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey.
      4. \n
      5. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, false, isImports,\nconditions).
      6. \n
      7. Return the object { resolved, exact: false }.
      8. \n
      \n
    4. \n
    \n
  6. \n
  7. Return the object { resolved: null, exact: true }.
  8. \n
\n
\n

PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, pattern,\ninternal, conditions)

\n
\n
    \n
  1. If target is a String, then\n
      \n
    1. If pattern is false, subpath has non-zero length and target\ndoes not end with \"/\", throw an Invalid Module Specifier error.
    2. \n
    3. If target does not start with \"./\", then\n
        \n
      1. If internal is true and target does not start with \"../\" or\n\"/\" and is not a valid URL, then\n
          \n
        1. If pattern is true, then\n
            \n
          1. Return PACKAGE_RESOLVE(target with every instance of\n\"*\" replaced by subpath, packageURL + \"/\")_.
          2. \n
          \n
        2. \n
        3. Return PACKAGE_RESOLVE(target + subpath,\npackageURL + \"/\")_.
        4. \n
        \n
      2. \n
      3. Otherwise, throw an Invalid Package Target error.
      4. \n
      \n
    4. \n
    5. If target split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments after the first segment, throw an\nInvalid Package Target error.
    6. \n
    7. Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
    8. \n
    9. Assert: resolvedTarget is contained in packageURL.
    10. \n
    11. If subpath split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments, throw an Invalid Module Specifier error.
    12. \n
    13. If pattern is true, then\n
        \n
      1. Return the URL resolution of resolvedTarget with every instance of\n\"*\" replaced with subpath.
      2. \n
      \n
    14. \n
    15. Otherwise,\n
        \n
      1. Return the URL resolution of the concatenation of subpath and\nresolvedTarget.
      2. \n
      \n
    16. \n
    \n
  2. \n
  3. Otherwise, if target is a non-null Object, then\n
      \n
    1. If exports contains any index property keys, as defined in ECMA-262\n6.1.7 Array Index, throw an Invalid Package Configuration error.
    2. \n
    3. For each property p of target, in object insertion order as,\n
        \n
      1. If p equals \"default\" or conditions contains an entry for p,\nthen\n
          \n
        1. Let targetValue be the value of the p property in target.
        2. \n
        3. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions).
        4. \n
        5. If resolved is equal to undefined, continue the loop.
        6. \n
        7. Return resolved.
        8. \n
        \n
      2. \n
      \n
    4. \n
    5. Return undefined.
    6. \n
    \n
  4. \n
  5. Otherwise, if target is an Array, then\n
      \n
    1. If _target.length is zero, return null.
    2. \n
    3. For each item targetValue in target, do\n
        \n
      1. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions), continuing the loop on any Invalid Package Target\nerror.
      2. \n
      3. If resolved is undefined, continue the loop.
      4. \n
      5. Return resolved.
      6. \n
      \n
    4. \n
    5. Return or throw the last fallback resolution null return or error.
    6. \n
    \n
  6. \n
  7. Otherwise, if target is null, return null.
  8. \n
  9. Otherwise throw an Invalid Package Target error.
  10. \n
\n
\n

ESM_FORMAT(url)

\n
\n
    \n
  1. Assert: url corresponds to an existing file.
  2. \n
  3. Let pjson be the result of READ_PACKAGE_SCOPE(url).
  4. \n
  5. If url ends in \".mjs\", then\n
      \n
    1. Return \"module\".
    2. \n
    \n
  6. \n
  7. If url ends in \".cjs\", then\n
      \n
    1. Return \"commonjs\".
    2. \n
    \n
  8. \n
  9. If pjson?.type exists and is \"module\", then\n
      \n
    1. If url ends in \".js\", then\n
        \n
      1. Return \"module\".
      2. \n
      \n
    2. \n
    3. Throw an Unsupported File Extension error.
    4. \n
    \n
  10. \n
  11. Otherwise,\n
      \n
    1. Throw an Unsupported File Extension error.
    2. \n
    \n
  12. \n
\n
\n

READ_PACKAGE_SCOPE(url)

\n
\n
    \n
  1. Let scopeURL be url.
  2. \n
  3. While scopeURL is not the file system root,\n
      \n
    1. Set scopeURL to the parent URL of scopeURL.
    2. \n
    3. If scopeURL ends in a \"node_modules\" path segment, return null.
    4. \n
    5. Let pjson be the result of READ_PACKAGE_JSON(scopeURL).
    6. \n
    7. If pjson is not null, then\n
        \n
      1. Return pjson.
      2. \n
      \n
    8. \n
    \n
  4. \n
  5. Return null.
  6. \n
\n
\n

READ_PACKAGE_JSON(packageURL)

\n
\n
    \n
  1. Let pjsonURL be the resolution of \"package.json\" within packageURL.
  2. \n
  3. If the file at pjsonURL does not exist, then\n
      \n
    1. Return null.
    2. \n
    \n
  4. \n
  5. If the file at packageURL does not parse as valid JSON, then\n
      \n
    1. Throw an Invalid Package Configuration error.
    2. \n
    \n
  6. \n
  7. Return the parsed JSON source of the file at pjsonURL.
  8. \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": "

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.

\n

The --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.

\n
$ 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.

", "properties": [ { "textRaw": "`url` {string} The absolute `file:` URL of the module.", "type": "string", "name": "url", "desc": "

This is defined exactly the same as it is in browsers providing the URL of the\ncurrent module file.

\n

This enables useful patterns such as relative file loading:

\n
import { readFileSync } from '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

Stability: 1 - Experimental

\n
\n

This feature is only available with the --experimental-import-meta-resolve\ncommand flag enabled.

\n\n

Provides a module-relative resolution function scoped to each module, returning\nthe URL string.

\n\n
const dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n
\n

import.meta.resolve also accepts a second argument which is the parent module\nfrom which to resolve from:

\n\n
await import.meta.resolve('./dep', import.meta.url);\n
\n

This function is asynchronous because the ES module resolver in Node.js is\nallowed to be asynchronous.

" } ] } ] } ] }