{ "type": "module", "source": "doc/api/esm.md", "introduced_in": "v8.5.0", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": [ "v23.1.0", "v22.12.0", "v20.18.3", "v18.20.5" ], "pr-url": "https://github.com/nodejs/node/pull/55333", "description": "Import attributes are no longer experimental." }, { "version": "v22.0.0", "pr-url": "https://github.com/nodejs/node/pull/52104", "description": "Drop support for import assertions." }, { "version": [ "v21.0.0", "v20.10.0", "v18.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/50140", "description": "Add experimental support for import attributes." }, { "version": [ "v20.0.0", "v18.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/44710", "description": "Module customization hooks are executed off the main thread." }, { "version": [ "v18.6.0", "v16.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/42623", "description": "Add support for chaining module customization hooks." }, { "version": [ "v17.1.0", "v16.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/40250", "description": "Add experimental support for import assertions." }, { "version": [ "v17.0.0", "v16.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/37468", "description": "Consolidate customization hooks, removed `getFormat`, `getSource`, `transformSource`, and `getGlobalPreloadCode` hooks added `load` and `globalPreload` hooks allowed returning `format` from either `resolve` or `load` hooks." }, { "version": [ "v15.3.0", "v14.17.0", "v12.22.0" ], "pr-url": "https://github.com/nodejs/node/pull/35781", "description": "Stabilize modules implementation." }, { "version": [ "v14.13.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/35249", "description": "Support for detection of CommonJS named exports." }, { "version": "v14.8.0", "pr-url": "https://github.com/nodejs/node/pull/34558", "description": "Unflag Top-Level Await." }, { "version": [ "v14.0.0", "v13.14.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/31974", "description": "Remove experimental modules warning." }, { "version": [ "v13.2.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/29866", "description": "Loading ECMAScript modules no longer requires a command-line flag." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26745", "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." } ] }, "stability": 2, "stabilityText": "Stable", "properties": [ { "textRaw": "Type: {Object}", "name": "meta", "type": "Object", "desc": "
The import.meta meta property is an Object that contains the following\nproperties. It is only supported in ES modules.
", "properties": [ { "textRaw": "Type: {string} The directory name of the current module.", "name": "dirname", "type": "string", "meta": { "added": [ "v21.2.0", "v20.11.0" ], "changes": [ { "version": [ "v24.0.0", "v22.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/58011", "description": "This property is no longer experimental." } ] }, "desc": "
This is the same as the path.dirname() of the import.meta.filename.
\n
\nCaveat: only present on
\nfile:modules.
", "shortDesc": "The directory name of the current module." }, { "textRaw": "Type: {string} The full absolute path and filename of the current module, with symlinks resolved.", "name": "filename", "type": "string", "meta": { "added": [ "v21.2.0", "v20.11.0" ], "changes": [ { "version": [ "v24.0.0", "v22.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/58011", "description": "This property is no longer experimental." } ] }, "desc": "
This is the same as the url.fileURLToPath() of the import.meta.url.
\n
\nCaveat only local modules support this property. Modules not using the\n
\nfile:protocol will not provide it.
", "shortDesc": "The full absolute path and filename of the current module, with symlinks resolved." }, { "textRaw": "Type: {string} The absolute `file:` URL of the module.", "name": "url", "type": "string", "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 'node:fs';\nconst buffer = readFileSync(new URL('./data.proto', import.meta.url));\n", "shortDesc": "The absolute `file:` URL of the module." }, { "textRaw": "Type: {boolean} `true` when the current module is the entry point of the current process; `false` otherwise.", "name": "main", "type": "boolean", "meta": { "added": [ "v24.2.0", "v22.18.0" ], "changes": [] }, "stability": 1, "stabilityText": "Early development", "desc": "
Equivalent to require.main === module in CommonJS.
\n
Analogous to Python's __name__ == \"__main__\".
\n
export function foo() {\n return 'Hello, world';\n}\n\nfunction main() {\n const message = foo();\n console.log(message);\n}\n\nif (import.meta.main) main();\n// `foo` can be imported from another module without possible side-effects from `main`\n", "shortDesc": "`true` when the current module is the entry point of the current process; `false` otherwise." } ], "methods": [ { "textRaw": "`import.meta.resolve(specifier)`", "name": "resolve", "type": "method", "meta": { "added": [ "v13.9.0", "v12.16.2" ], "changes": [ { "version": [ "v20.6.0", "v18.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/49028", "description": "No longer behind `--experimental-import-meta-resolve` CLI flag, except for the non-standard `parentURL` parameter." }, { "version": [ "v20.6.0", "v18.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/49038", "description": "This API no longer throws when targeting `file:` URLs that do not map to an existing file on the local FS." }, { "version": [ "v20.0.0", "v18.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/44710", "description": "This API now returns a string synchronously instead of a Promise." }, { "version": [ "v16.2.0", "v14.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/38587", "description": "Add support for WHATWG `URL` object to `parentURL` parameter." } ] }, "stability": 1.2, "stabilityText": "Release candidate", "signatures": [ { "params": [ { "textRaw": "`specifier` {string} The module specifier to resolve relative to the current module.", "name": "specifier", "type": "string", "desc": "The module specifier to resolve relative to the current module." } ], "return": { "textRaw": "Returns: {string} The absolute URL string that the specifier would resolve to.", "name": "return", "type": "string", "desc": "The absolute URL string that the specifier would resolve to." } } ], "desc": "
import.meta.resolve is a module-relative resolution function scoped to\neach module, returning the URL string.
\n
const dependencyAsset = import.meta.resolve('component-lib/asset.css');\n// file:///app/node_modules/component-lib/asset.css\nimport.meta.resolve('./dep.js');\n// file:///app/dep.js\n\n
All features of the Node.js module resolution are supported. Dependency\nresolutions are subject to the permitted exports resolutions within the package.
\n
Caveats:
\n
require.resolve.\n
Non-standard API:
\n
When using the --experimental-import-meta-resolve flag, that function accepts\na second argument:
\n
parent <string> | <URL> An optional absolute parent module URL to resolve from. Default: import.meta.url" } ] } ], "miscs": [ { "textRaw": "Modules: ECMAScript modules", "name": "Modules: ECMAScript modules", "introduced_in": "v8.5.0", "type": "misc", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": [ "v23.1.0", "v22.12.0", "v20.18.3", "v18.20.5" ], "pr-url": "https://github.com/nodejs/node/pull/55333", "description": "Import attributes are no longer experimental." }, { "version": "v22.0.0", "pr-url": "https://github.com/nodejs/node/pull/52104", "description": "Drop support for import assertions." }, { "version": [ "v21.0.0", "v20.10.0", "v18.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/50140", "description": "Add experimental support for import attributes." }, { "version": [ "v20.0.0", "v18.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/44710", "description": "Module customization hooks are executed off the main thread." }, { "version": [ "v18.6.0", "v16.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/42623", "description": "Add support for chaining module customization hooks." }, { "version": [ "v17.1.0", "v16.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/40250", "description": "Add experimental support for import assertions." }, { "version": [ "v17.0.0", "v16.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/37468", "description": "Consolidate customization hooks, removed `getFormat`, `getSource`, `transformSource`, and `getGlobalPreloadCode` hooks added `load` and `globalPreload` hooks allowed returning `format` from either `resolve` or `load` hooks." }, { "version": [ "v15.3.0", "v14.17.0", "v12.22.0" ], "pr-url": "https://github.com/nodejs/node/pull/35781", "description": "Stabilize modules implementation." }, { "version": [ "v14.13.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/35249", "description": "Support for detection of CommonJS named exports." }, { "version": "v14.8.0", "pr-url": "https://github.com/nodejs/node/pull/34558", "description": "Unflag Top-Level Await." }, { "version": [ "v14.0.0", "v13.14.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/31974", "description": "Remove experimental modules warning." }, { "version": [ "v13.2.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/29866", "description": "Loading ECMAScript modules no longer requires a command-line flag." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26745", "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." } ] }, "stability": 2, "stabilityText": "Stable", "miscs": [ { "textRaw": "Introduction", "name": "introduction", "type": "misc", "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
", "displayName": "Introduction" }, { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "
Node.js has two module systems: CommonJS modules and ECMAScript modules.
\n
Authors can tell Node.js to interpret JavaScript as an ES module via the .mjs\nfile extension, the package.json \"type\" field with a value \"module\",\nor the --input-type flag with a value of \"module\". These are explicit\nmarkers of code being intended to run as an ES module.
\n
Inversely, authors can explicitly tell Node.js to interpret JavaScript as\nCommonJS via the .cjs file extension, the package.json \"type\" field\nwith a value \"commonjs\", or the --input-type flag with a value of\n\"commonjs\".
\n
When code lacks explicit markers for either module system, Node.js will inspect\nthe source code of a module to look for ES module syntax. If such syntax is\nfound, Node.js will run the code as an ES module; otherwise it will run the\nmodule as CommonJS. See Determining module system for more details.
\n
" }, { "textRaw": "Packages", "name": "packages", "type": "misc", "desc": "
This section was moved to Modules: Packages.
", "displayName": "Packages" }, { "textRaw": "`import` Specifiers", "name": "`import`_specifiers", "type": "misc", "modules": [ { "textRaw": "Terminology", "name": "terminology", "type": "module", "desc": "
The specifier of an import statement is the string after the from keyword,\ne.g. 'node:path' in import { sep } from 'node:path'. Specifiers are also\nused in export from statements, and as the argument to an import()\nexpression.
\n
There are three types of specifiers:
\n
Relative 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.
\n
Bare specifier resolutions are handled by the Node.js module\nresolution and loading algorithm.\nAll other specifier resolutions are always only resolved with\nthe standard relative URL resolution semantics.
\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.
", "displayName": "Terminology" }, { "textRaw": "Mandatory file extensions", "name": "mandatory_file_extensions", "type": "module", "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.
", "displayName": "Mandatory file extensions" }, { "textRaw": "URLs", "name": "urls", "type": "module", "desc": "
ES modules are resolved and cached as URLs. This means that special characters\nmust be percent-encoded, such as # with %23 and ? with %3F.
\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", "type": "module", "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.
", "displayName": "`file:` URLs" }, { "textRaw": "`data:` imports", "name": "`data:`_imports", "type": "module", "meta": { "added": [ "v12.10.0" ], "changes": [] }, "desc": "
data: URLs are supported for importing with the following MIME types:
\n
text/javascript for ES modulesapplication/json for JSONapplication/wasm for Wasm\n
import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"' with { type: 'json' };\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.
", "displayName": "`data:` imports" }, { "textRaw": "`node:` imports", "name": "`node:`_imports", "type": "module", "meta": { "added": [ "v14.13.1", "v12.20.0" ], "changes": [ { "version": [ "v16.0.0", "v14.18.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\n
", "displayName": "`node:` imports" } ], "displayName": "URLs" } ], "displayName": "`import` Specifiers" }, { "textRaw": "Import attributes", "name": "import_attributes", "type": "misc", "meta": { "added": [ "v17.1.0", "v16.14.0" ], "changes": [ { "version": [ "v21.0.0", "v20.10.0", "v18.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/50140", "description": "Switch from Import Assertions to Import Attributes." } ] }, "desc": "
Import attributes are an inline syntax for module import\nstatements to pass on more information alongside the module specifier.
\n
import fooData from './foo.json' with { type: 'json' };\n\nconst { default: barData } =\n await import('./bar.json', { with: { type: 'json' } });\n\n
Node.js only supports the type attribute, for which it supports the following values:
\n
Attribute type | \nNeeded for | \n
|---|---|
'json' | \nJSON modules | \n
\n
The type: 'json' attribute is mandatory when importing JSON modules.
", "displayName": "Import attributes" }, { "textRaw": "Built-in modules", "name": "built-in_modules", "type": "misc", "desc": "
Built-in 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 built-in modules are updated only by calling\nmodule.syncBuiltinESMExports().
\n
import EventEmitter from 'node:events';\nconst e = new EventEmitter();\n\n
import { 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\n
import 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\n
\nWhen importing built-in modules, all the named exports (i.e. properties of the module exports object)\nare populated even if they are not individually accessed.\nThis can make initial imports of built-in modules slightly slower compared to loading them with\n
\nrequire()orprocess.getBuiltinModule(), where the module exports object is evaluated immediately,\nbut some of its properties may only be initialized when first accessed individually.
", "displayName": "Built-in modules" }, { "textRaw": "`import()` expressions", "name": "`import()`_expressions", "type": "misc", "desc": "
Dynamic import() provides an asynchronous way to import modules. It is\nsupported in both CommonJS and ES modules, and can be used to load both CommonJS\nand ES modules.
", "displayName": "`import()` expressions" }, { "textRaw": "Interoperability with CommonJS", "name": "interoperability_with_commonjs", "type": "misc", "modules": [ { "textRaw": "`import` statements", "name": "`import`_statements", "type": "module", "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.
", "displayName": "`import` statements" }, { "textRaw": "`require`", "name": "`require`", "type": "module", "desc": "
The CommonJS module require currently only supports loading synchronous ES\nmodules (that is, ES modules that do not use top-level await).
\n
See Loading ECMAScript modules using require() for details.
", "displayName": "`require`" }, { "textRaw": "CommonJS Namespaces", "name": "commonjs_namespaces", "type": "module", "meta": { "added": [ "v14.13.0" ], "changes": [ { "version": "v23.0.0", "pr-url": "https://github.com/nodejs/node/pull/53848", "description": "Added `'module.exports'` export marker to CJS namespaces." } ] }, "desc": "
CommonJS modules consist of a module.exports object which can be of any type.
\n
To support this, when importing CommonJS from an ECMAScript module, a namespace\nwrapper for the CommonJS module is constructed, which always provides a\ndefault export key pointing to the CommonJS module.exports value.
\n
In addition, a heuristic static analysis is performed against the source text of\nthe CommonJS module to get a best-effort static list of exports to provide on\nthe namespace from values on module.exports. This is necessary since these\nnamespaces must be constructed prior to the evaluation of the CJS module.
\n
These CommonJS namespace objects also provide the default export as a\n'module.exports' named export, in order to unambiguously indicate that their\nrepresentation in CommonJS uses this value, and not the namespace value. This\nmirrors the semantics of the handling of the 'module.exports' export name in\nrequire(esm) interop support.
\n
When importing a CommonJS module, it can be reliably imported using the ES\nmodule default import or its corresponding sugar syntax:
\n
import { default as cjs } from 'cjs';\n// Identical to the above\nimport cjsSugar from 'cjs';\n\nconsole.log(cjs);\nconsole.log(cjs === cjsSugar);\n// Prints:\n// <module.exports>\n// true\n\n
This Module Namespace Exotic Object can be directly observed either when using\nimport * as m from 'cjs' or a dynamic import:
\n
import * as m from 'cjs';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n// [Module] { default: <module.exports>, 'module.exports': <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
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:\n// [Module] {\n// default: { name: 'exported' },\n// 'module.exports': { name: 'exported' },\n// name: 'exported'\n// }\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 merve for the exact\nsemantics implemented.
", "displayName": "CommonJS Namespaces" }, { "textRaw": "Differences between ES modules and CommonJS", "name": "differences_between_es_modules_and_commonjs", "type": "module", "modules": [ { "textRaw": "No `require`, `exports`, or `module.exports`", "name": "no_`require`,_`exports`,_or_`module.exports`", "type": "module", "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().
", "displayName": "No `require`, `exports`, or `module.exports`" }, { "textRaw": "No `__filename` or `__dirname`", "name": "no_`__filename`_or_`__dirname`", "type": "module", "desc": "
These CommonJS variables are not available in ES modules.
\n
__filename and __dirname use cases can be replicated via\nimport.meta.filename and import.meta.dirname.
", "displayName": "No `__filename` or `__dirname`" }, { "textRaw": "No Addon Loading", "name": "no_addon_loading", "type": "module", "desc": "
Addons are not currently supported with ES module imports.
\n
They can instead be loaded with module.createRequire() or\nprocess.dlopen.
", "displayName": "No Addon Loading" }, { "textRaw": "No `require.main`", "name": "no_`require.main`", "type": "module", "desc": "
To replace require.main === module, there is the import.meta.main API.
", "displayName": "No `require.main`" }, { "textRaw": "No `require.resolve`", "name": "no_`require.resolve`", "type": "module", "desc": "
Relative resolution can be handled via new URL('./local', import.meta.url).
\n
For a complete require.resolve replacement, there is the\nimport.meta.resolve API.
\n
Alternatively module.createRequire() can be used.
", "displayName": "No `require.resolve`" }, { "textRaw": "No `NODE_PATH`", "name": "no_`node_path`", "type": "module", "desc": "
NODE_PATH is not part of resolving import specifiers. Please use symlinks\nif this behavior is desired.
", "displayName": "No `NODE_PATH`" }, { "textRaw": "No `require.extensions`", "name": "no_`require.extensions`", "type": "module", "desc": "
require.extensions is not used by import. Module customization hooks can\nprovide a replacement.
", "displayName": "No `require.extensions`" }, { "textRaw": "No `require.cache`", "name": "no_`require.cache`", "type": "module", "desc": "
require.cache is not used by import as the ES module loader has its own\nseparate cache.
\n
", "displayName": "No `require.cache`" } ], "displayName": "Differences between ES modules and CommonJS" } ], "displayName": "Interoperability with CommonJS" }, { "textRaw": "JSON modules", "name": "json_modules", "type": "misc", "meta": { "changes": [ { "version": [ "v23.1.0", "v22.12.0", "v20.18.3", "v18.20.5" ], "pr-url": "https://github.com/nodejs/node/pull/55333", "description": "JSON modules are no longer experimental." } ] }, "desc": "
JSON files can be referenced by import:
\n
import packageConfig from './package.json' with { type: 'json' };\n\n
The with { type: 'json' } syntax is mandatory; see Import Attributes.
\n
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.
\n
", "displayName": "JSON modules" }, { "textRaw": "Wasm modules", "name": "wasm_modules", "type": "misc", "meta": { "changes": [ { "version": [ "v24.5.0", "v22.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/57038", "description": "Wasm modules no longer require the `--experimental-wasm-modules` flag." } ] }, "desc": "
Importing both WebAssembly module instances and WebAssembly source phase\nimports is supported.
\n
Both of these integrations are in line with the\nES Module Integration Proposal for WebAssembly.
", "modules": [ { "textRaw": "Wasm Source Phase Imports", "name": "wasm_source_phase_imports", "type": "module", "meta": { "added": [ "v24.0.0" ], "changes": [] }, "stability": 1.2, "stabilityText": "Release candidate", "desc": "
The Source Phase Imports proposal allows the import source keyword\ncombination to import a WebAssembly.Module object directly, instead of getting\na module instance already instantiated with its dependencies.
\n
This is useful when needing custom instantiations for Wasm, while still\nresolving and loading it through the ES module integration.
\n
For example, to create multiple instances of a module, or to pass custom imports\ninto a new instance of library.wasm:
\n
import source libraryModule from './library.wasm';\n\nconst instance1 = await WebAssembly.instantiate(libraryModule, importObject1);\n\nconst instance2 = await WebAssembly.instantiate(libraryModule, importObject2);\n\n
In addition to the static source phase, there is also a dynamic variant of the\nsource phase via the import.source dynamic phase import syntax:
\n
const dynamicLibrary = await import.source('./library.wasm');\n\nconst instance = await WebAssembly.instantiate(dynamicLibrary, importObject);\n", "displayName": "Wasm Source Phase Imports" }, { "textRaw": "JavaScript String Builtins", "name": "javascript_string_builtins", "type": "module", "meta": { "added": [ "v24.5.0", "v22.19.0" ], "changes": [] }, "stability": 1.2, "stabilityText": "Release candidate", "desc": "
When importing WebAssembly modules, the\nWebAssembly JS String Builtins Proposal is automatically enabled through the\nESM Integration. This allows WebAssembly modules to directly use efficient\ncompile-time string builtins from the wasm:js-string namespace.
\n
For example, the following Wasm module exports a string getLength function using\nthe wasm:js-string length builtin:
\n
(module\n ;; Compile-time import of the string length builtin.\n (import \"wasm:js-string\" \"length\" (func $string_length (param externref) (result i32)))\n\n ;; Define getLength, taking a JS value parameter assumed to be a string,\n ;; calling string length on it and returning the result.\n (func $getLength (param $str externref) (result i32)\n local.get $str\n call $string_length\n )\n\n ;; Export the getLength function.\n (export \"getLength\" (func $get_length))\n)\n\n
import { getLength } from './string-len.wasm';\ngetLength('foo'); // Returns 3.\n\n
Wasm builtins are compile-time imports that are linked during module compilation\nrather than during instantiation. They do not behave like normal module graph\nimports and they cannot be inspected via WebAssembly.Module.imports(mod)\nor virtualized unless recompiling the module using the direct\nWebAssembly.compile API with string builtins disabled.
\n
String constants may also be imported from the wasm:js/string-constants builtin\nimport URL, allowing static JS string globals to be defined:
\n
(module\n (import \"wasm:js/string-constants\" \"hello\" (global $hello externref))\n)\n\n
Importing a module in the source phase before it has been instantiated will also\nuse the compile-time builtins automatically:
\n
import source mod from './string-len.wasm';\nconst { exports: { getLength } } = await WebAssembly.instantiate(mod, {});\ngetLength('foo'); // Also returns 3.\n", "displayName": "JavaScript String Builtins" }, { "textRaw": "Wasm Instance Phase Imports", "name": "wasm_instance_phase_imports", "type": "module", "stability": 1.1, "stabilityText": "Active development", "desc": "
Instance imports allow any .wasm files to be imported as normal modules,\nsupporting their module imports in turn.
\n
For example, an index.js containing:
\n
import * as M from './library.wasm';\nconsole.log(M);\n\n
executed under:
\n
node index.mjs\n\n
would provide the exports interface for the instantiation of library.wasm.
", "displayName": "Wasm Instance Phase Imports" }, { "textRaw": "Reserved Wasm Namespaces", "name": "reserved_wasm_namespaces", "type": "module", "meta": { "added": [ "v24.5.0", "v22.19.0" ], "changes": [] }, "desc": "
When importing WebAssembly module instances, they cannot use import module\nnames or import/export names that start with reserved prefixes:
\n
wasm-js: - reserved in all module import names, module names and export\nnames.wasm: - reserved in module import names and export names (imported module\nnames are allowed in order to support future builtin polyfills).\n
Importing a module using the above reserved names will throw a\nWebAssembly.LinkError.
\n
", "displayName": "Reserved Wasm Namespaces" } ], "displayName": "Wasm modules" }, { "textRaw": "Top-level `await`", "name": "top-level_`await`", "type": "misc", "meta": { "added": [ "v14.8.0" ], "changes": [] }, "desc": "
The await keyword may be used in the top level body of an ECMAScript module.
\n
Assuming an a.mjs with
\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
If a top level await expression never resolves, the node process will exit\nwith a 13 status code.
\n
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\n
", "displayName": "Top-level `await`" }, { "textRaw": "Loaders", "name": "loaders", "type": "misc", "desc": "
The former Loaders documentation is now at\nModules: Customization hooks.
", "displayName": "Loaders" }, { "textRaw": "Resolution and loading algorithm", "name": "resolution_and_loading_algorithm", "type": "misc", "modules": [ { "textRaw": "Features", "name": "features", "type": "module", "desc": "
The default resolver has the following properties:
\n
\n
The default loader has the following properties
\n
node: URLsdata: URLsfile: module loadingfile: loading\n(supports only .cjs, .js, and .mjs)", "displayName": "Features" }, { "textRaw": "Resolution algorithm", "name": "resolution_algorithm", "type": "module", "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 resolution algorithm determines the full resolved URL for a module\nload, along with its suggested module format. The resolution algorithm\ndoes not determine whether the resolved URL protocol can be loaded,\nor whether the file extensions are permitted, instead these validations\nare applied by Node.js during the load phase\n(for example, if it was asked to load a URL that has a protocol that is\nnot file:, data: or node:.
\n
The algorithm also tries to determine the format of the file based\non the extension (see ESM_FILE_FORMAT algorithm below). If it does\nnot recognize the file extension (eg if it is not .mjs, .cjs, or\n.json), then a format of undefined is returned,\nwhich will throw during the load phase.
\n
The algorithm to determine the module format of a resolved URL is\nprovided by ESM_FILE_FORMAT, which returns the unique module\nformat for any file. The \"module\" format is returned for an ECMAScript\nModule, while the \"commonjs\" format is used to indicate loading through the\nlegacy CommonJS loader. Additional formats such as \"addon\" can be extended in\nfuture updates.
\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
", "displayName": "Resolution algorithm" }, { "textRaw": "Resolution Algorithm Specification", "name": "resolution_algorithm_specification", "type": "module", "desc": "
ESM_RESOLVE(specifier, parentURL)
\n
\n\n
\n- Let resolved be undefined.
\n- If specifier is a valid URL, then\n
\n\n
\n- Set resolved to the result of parsing and reserializing\nspecifier as a URL.
\n- Otherwise, if specifier starts with \"/\", \"./\", or \"../\", then\n
\n\n
\n- Set resolved to the URL resolution of specifier relative to\nparentURL.
\n- Otherwise, if specifier starts with \"#\", then\n
\n\n
\n- Set resolved to the result of\nPACKAGE_IMPORTS_RESOLVE(specifier,\nparentURL, defaultConditions).
\n- Otherwise,\n
\n\n
\n- Note: specifier is now a bare specifier.
\n- Set resolved the result of\nPACKAGE_RESOLVE(specifier, parentURL).
\n- Let format be undefined.
\n- If resolved is a \"file:\" URL, then\n
\n\n
\n- If resolved contains any percent encodings of \"/\" or \"\\\" (\"%2F\"\nand \"%5C\" respectively), then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- If the file at resolved is a directory, then\n
\n\n
\n- Throw an Unsupported Directory Import error.
\n- If the file at resolved does not exist, then\n
\n\n
\n- Throw a Module Not Found error.
\n- Set resolved to the real path of resolved, maintaining the\nsame URL querystring and fragment components.
\n- Set format to the result of ESM_FILE_FORMAT(resolved).
\n- Otherwise,\n
\n\n
\n- Set format the module format of the content type associated with the\nURL resolved.
\n- Return format and resolved to the loading phase
\n
\n
PACKAGE_RESOLVE(packageSpecifier, parentURL)
\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- 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 packageName, 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
\n
PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)
\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
\n
PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)
\n
Note: This function is directly invoked by the CommonJS resolution algorithm.
\n
\n\n
\n- If exports is an Object with both a key starting with \".\" and a key not\nstarting with \".\", throw an Invalid Package Configuration error.
\n- If subpath is equal to \".\", then\n
\n\n
\n- Let mainExport be undefined.
\n- If exports is a String or Array, or an Object containing no keys\nstarting with \".\", then\n
\n\n
\n- Set mainExport to exports.
\n- Otherwise if exports is an Object containing a \".\" property, then\n
\n\n
\n- Set mainExport to exports[\".\"].
\n- If mainExport is not undefined, then\n
\n\n
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, null, false, conditions).
\n- If resolved is not null or undefined, return resolved.
\n- Otherwise, if exports is an Object and all keys of exports start with\n\".\", then\n
\n\n
\n- Assert: subpath begins with \"./\".
\n- Let resolved be the result of PACKAGE_IMPORTS_EXPORTS_RESOLVE(\nsubpath, exports, packageURL, false, conditions).
\n- If resolved is not null or undefined, return resolved.
\n- Throw a Package Path Not Exported error.
\n
\n
PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)
\n
Note: This function is directly invoked by the CommonJS resolution algorithm.
\n
\n\n
\n- Assert: specifier begins with \"#\".
\n- If specifier is exactly equal to \"#\", 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
\n
PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL,\nisImports, conditions)
\n
\n\n
\n- If matchKey ends in \"/\", then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- If matchKey is a key of matchObj and does not contain \"*\", then\n
\n\n
\n- Let target be the value of matchObj[matchKey].
\n- Return the result of PACKAGE_TARGET_RESOLVE(packageURL,\ntarget, null, isImports, conditions).
\n- Let expansionKeys be the list of keys of matchObj containing only a\nsingle \"*\", sorted by the sorting function PATTERN_KEY_COMPARE\nwhich orders in descending order of specificity.
\n- For each key expansionKey in expansionKeys, do\n
\n\n
\n- Let patternBase be the substring of expansionKey up to but excluding\nthe first \"*\" character.
\n- If matchKey starts with but is not equal to patternBase, then\n
\n\n
\n- Let patternTrailer be the substring of expansionKey from the\nindex after the first \"*\" character.
\n- If patternTrailer has zero length, or if matchKey ends with\npatternTrailer and the length of matchKey is greater than or\nequal to the length of expansionKey, then\n
\n\n
\n- Let target be the value of matchObj[expansionKey].
\n- Let patternMatch be the substring of matchKey starting at the\nindex of the length of patternBase up to the length of\nmatchKey minus the length of patternTrailer.
\n- Return the result of PACKAGE_TARGET_RESOLVE(packageURL,\ntarget, patternMatch, isImports, conditions).
\n- Return null.
\n
\n
PATTERN_KEY_COMPARE(keyA, keyB)
\n
\n\n
\n- Assert: keyA contains only a single \"*\".
\n- Assert: keyB contains only a single \"*\".
\n- Let baseLengthA be the index of \"*\" in keyA.
\n- Let baseLengthB be the index of \"*\" in keyB.
\n- If baseLengthA is greater than baseLengthB, return -1.
\n- If baseLengthB is greater than baseLengthA, 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
\n
PACKAGE_TARGET_RESOLVE(packageURL, target, patternMatch,\nisImports, conditions)
\n
\n\n
\n- If target is a String, then\n
\n\n
\n- If target does not start with \"./\", then\n
\n\n
\n- If isImports is false, or if target starts with \"../\" or\n\"/\", or if target is a valid URL, then\n
\n\n
\n- Throw an Invalid Package Target error.
\n- If patternMatch is a String, then\n
\n\n
\n- Return PACKAGE_RESOLVE(target with every instance of \"*\"\nreplaced by patternMatch, packageURL + \"/\").
\n- Return PACKAGE_RESOLVE(target, packageURL + \"/\").
\n- If target split on \"/\" or \"\\\" contains any \"\", \".\", \"..\",\nor \"node_modules\" segments after the first \".\" segment, case\ninsensitive and including percent encoded variants, throw an Invalid\nPackage Target error.
\n- Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
\n- Assert: packageURL is contained in resolvedTarget.
\n- If patternMatch is null, then\n
\n\n
\n- Return resolvedTarget.
\n- If patternMatch split on \"/\" or \"\\\" contains any \"\", \".\",\n\"..\", or \"node_modules\" segments, case insensitive and including\npercent encoded variants, throw an Invalid Module Specifier error.
\n- Return the URL resolution of resolvedTarget with every instance of\n\"*\" replaced with patternMatch.
\n- Otherwise, if target is a non-null Object, then\n
\n\n
\n- If target contains any index property keys, as defined in ECMA-262\n6.1.7 Array Index, throw an Invalid Package Configuration error.
\n- For each property p of target, in object insertion order as,\n
\n\n
\n- If p equals \"default\" or conditions contains an entry for p,\nthen\n
\n\n
\n- Let targetValue be the value of the p property in target.
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, patternMatch, isImports,\nconditions).
\n- If resolved is equal to undefined, continue the loop.
\n- Return resolved.
\n- Return undefined.
\n- Otherwise, if target is an Array, then\n
\n\n
\n- If _target.length is zero, return null.
\n- For each item targetValue in target, do\n
\n\n
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, patternMatch, isImports,\nconditions), continuing the loop on any Invalid Package Target\nerror.
\n- If resolved is undefined, continue the loop.
\n- Return resolved.
\n- Return or throw the last fallback resolution null return or error.
\n- Otherwise, if target is null, return null.
\n- Otherwise throw an Invalid Package Target error.
\n
\n
ESM_FILE_FORMAT(url)
\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- If url ends in\n\".wasm\", then\n
\n\n
\n- Return \"wasm\".
\n- If
\n--experimental-addon-modulesis enabled and url ends in\n\".node\", then\n\n
\n- Return \"addon\".
\n- Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(url).
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- Let packageType be null.
\n- If pjson?.type is \"module\" or \"commonjs\", then\n
\n\n
\n- Set packageType to pjson.type.
\n- If url ends in \".js\", then\n
\n\n
\n- If packageType is not null, then\n
\n\n
\n- Return packageType.
\n- If the result of DETECT_MODULE_SYNTAX(source) is true, then\n
\n\n
\n- Return \"module\".
\n- Return \"commonjs\".
\n- If url does not have any extension, then\n
\n\n
\n- If packageType is \"module\" and the file at url contains the\n\"application/wasm\" content type header for a WebAssembly module, then\n
\n\n
\n- Return \"wasm\".
\n- If packageType is not null, then\n
\n\n
\n- Return packageType.
\n- If the result of DETECT_MODULE_SYNTAX(source) is true, then\n
\n\n
\n- Return \"module\".
\n- Return \"commonjs\".
\n- Return undefined (will throw during load phase).
\n
\n
LOOKUP_PACKAGE_SCOPE(url)
\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
\n
READ_PACKAGE_JSON(packageURL)
\n
\n\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
DETECT_MODULE_SYNTAX(source)
\n
\n\n
\n- Parse source as an ECMAScript module.
\n- If the parse is successful, then\n
\n\n
\n- If source contains top-level
\nawait, staticimportorexport\nstatements, orimport.meta, return true.- If source contains a top-level lexical declaration (
\nconst,let,\norclass) of any of the CommonJS wrapper variables (require,\nexports,module,__filename, or__dirname) then return true.- Return false.
\n
", "displayName": "Resolution Algorithm Specification" }, { "textRaw": "Customizing ESM specifier resolution algorithm", "name": "customizing_esm_specifier_resolution_algorithm", "type": "module", "desc": "
Module customization hooks provide a mechanism for customizing the ESM\nspecifier resolution algorithm. An example that provides CommonJS-style\nresolution for ESM specifiers is commonjs-extension-resolution-loader.
", "displayName": "Customizing ESM specifier resolution algorithm" } ], "displayName": "Resolution and loading algorithm" } ], "properties": [ { "textRaw": "Type: {Object}", "name": "meta", "type": "Object", "desc": "
The import.meta meta property is an Object that contains the following\nproperties. It is only supported in ES modules.
", "properties": [ { "textRaw": "Type: {string} The directory name of the current module.", "name": "dirname", "type": "string", "meta": { "added": [ "v21.2.0", "v20.11.0" ], "changes": [ { "version": [ "v24.0.0", "v22.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/58011", "description": "This property is no longer experimental." } ] }, "desc": "
This is the same as the path.dirname() of the import.meta.filename.
\n
\nCaveat: only present on
\nfile:modules.
", "shortDesc": "The directory name of the current module." }, { "textRaw": "Type: {string} The full absolute path and filename of the current module, with symlinks resolved.", "name": "filename", "type": "string", "meta": { "added": [ "v21.2.0", "v20.11.0" ], "changes": [ { "version": [ "v24.0.0", "v22.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/58011", "description": "This property is no longer experimental." } ] }, "desc": "
This is the same as the url.fileURLToPath() of the import.meta.url.
\n
\nCaveat only local modules support this property. Modules not using the\n
\nfile:protocol will not provide it.
", "shortDesc": "The full absolute path and filename of the current module, with symlinks resolved." }, { "textRaw": "Type: {string} The absolute `file:` URL of the module.", "name": "url", "type": "string", "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 'node:fs';\nconst buffer = readFileSync(new URL('./data.proto', import.meta.url));\n", "shortDesc": "The absolute `file:` URL of the module." }, { "textRaw": "Type: {boolean} `true` when the current module is the entry point of the current process; `false` otherwise.", "name": "main", "type": "boolean", "meta": { "added": [ "v24.2.0", "v22.18.0" ], "changes": [] }, "stability": 1, "stabilityText": "Early development", "desc": "
Equivalent to require.main === module in CommonJS.
\n
Analogous to Python's __name__ == \"__main__\".
\n
export function foo() {\n return 'Hello, world';\n}\n\nfunction main() {\n const message = foo();\n console.log(message);\n}\n\nif (import.meta.main) main();\n// `foo` can be imported from another module without possible side-effects from `main`\n", "shortDesc": "`true` when the current module is the entry point of the current process; `false` otherwise." } ], "methods": [ { "textRaw": "`import.meta.resolve(specifier)`", "name": "resolve", "type": "method", "meta": { "added": [ "v13.9.0", "v12.16.2" ], "changes": [ { "version": [ "v20.6.0", "v18.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/49028", "description": "No longer behind `--experimental-import-meta-resolve` CLI flag, except for the non-standard `parentURL` parameter." }, { "version": [ "v20.6.0", "v18.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/49038", "description": "This API no longer throws when targeting `file:` URLs that do not map to an existing file on the local FS." }, { "version": [ "v20.0.0", "v18.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/44710", "description": "This API now returns a string synchronously instead of a Promise." }, { "version": [ "v16.2.0", "v14.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/38587", "description": "Add support for WHATWG `URL` object to `parentURL` parameter." } ] }, "stability": 1.2, "stabilityText": "Release candidate", "signatures": [ { "params": [ { "textRaw": "`specifier` {string} The module specifier to resolve relative to the current module.", "name": "specifier", "type": "string", "desc": "The module specifier to resolve relative to the current module." } ], "return": { "textRaw": "Returns: {string} The absolute URL string that the specifier would resolve to.", "name": "return", "type": "string", "desc": "The absolute URL string that the specifier would resolve to." } } ], "desc": "
import.meta.resolve is a module-relative resolution function scoped to\neach module, returning the URL string.
\n
const dependencyAsset = import.meta.resolve('component-lib/asset.css');\n// file:///app/node_modules/component-lib/asset.css\nimport.meta.resolve('./dep.js');\n// file:///app/dep.js\n\n
All features of the Node.js module resolution are supported. Dependency\nresolutions are subject to the permitted exports resolutions within the package.
\n
Caveats:
\n
require.resolve.\n
Non-standard API:
\n
When using the --experimental-import-meta-resolve flag, that function accepts\na second argument:
\n
parent <string> | <URL> An optional absolute parent module URL to resolve from. Default: import.meta.url" } ] } ] } ] }