{ "type": "module", "source": "doc/api/esm.md", "introduced_in": "v8.5.0", "stability": 1, "stabilityText": "Experimental", "properties": [ { "textRaw": "`meta` {Object}", "type": "Object", "name": "meta", "desc": "

The import.meta metaproperty is an Object that contains the following\nproperty:

\n" } ], "miscs": [ { "textRaw": "ECMAScript Modules", "name": "ECMAScript Modules", "introduced_in": "v8.5.0", "type": "misc", "stability": 1, "stabilityText": "Experimental", "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

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

\n

Node.js contains support for ES Modules based upon the\nNode.js EP for ES Modules and the ECMAScript-modules implementation.

\n

Expect major changes in the implementation including interoperability support,\nspecifier resolution, and default behavior.

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

Experimental support for ECMAScript modules is enabled by default.\nNode.js will treat the following as ES modules when passed to node as the\ninitial input, or when referenced by import statements within ES module code:

\n\n

Node.js will treat as CommonJS all other forms of input, such as .js files\nwhere the nearest parent package.json file contains no top-level \"type\"\nfield, or string input without the flag --input-type. This behavior is to\npreserve backward compatibility. However, now that Node.js supports both\nCommonJS and ES modules, it is best to be explicit whenever possible. Node.js\nwill treat the following as CommonJS when passed to node as the initial input,\nor when referenced by import statements within ES module code:

\n", "miscs": [ { "textRaw": "`package.json` `\"type\"` field", "name": "`package.json`_`\"type\"`_field", "desc": "

Files ending with .js or lacking any extension will be loaded as ES modules\nwhen the nearest parent package.json file contains a top-level field \"type\"\nwith a value of \"module\".

\n

The nearest parent package.json is defined as the first package.json found\nwhen searching in the current folder, that folder’s parent, and so on up\nuntil the root of the volume is reached.

\n\n
// package.json\n{\n  \"type\": \"module\"\n}\n
\n
# In same folder as above package.json\nnode my-app.js # Runs as ES module\n
\n

If the nearest parent package.json lacks a \"type\" field, or contains\n\"type\": \"commonjs\", extensionless and .js files are treated as CommonJS.\nIf the volume root is reached and no package.json is found,\nNode.js defers to the default, a package.json with no \"type\"\nfield. \"Extensionless\" refers to file paths which do not contain\nan extension as opposed to optionally dropping a file extension in a specifier.

\n

import statements of .js and extensionless files are treated as ES modules\nif the nearest parent package.json contains \"type\": \"module\".

\n
// my-app.js, part of the same example as above\nimport './startup.js'; // Loaded as ES module because of package.json\n
\n

Package authors should include the \"type\" field, even in packages where all\nsources are CommonJS. Being explicit about the type of the package will\nfuture-proof the package in case the default type of Node.js ever changes, and\nit will also make things easier for build tools and loaders to determine how the\nfiles in the package should be interpreted.

\n

Regardless of the value of the \"type\" field, .mjs files are always treated\nas ES modules and .cjs files are always treated as CommonJS.

", "type": "misc", "displayName": "`package.json` `\"type\"` field" }, { "textRaw": "Package Scope and File Extensions", "name": "package_scope_and_file_extensions", "desc": "

A folder containing a package.json file, and all subfolders below that\nfolder down until the next folder containing another package.json, is\nconsidered a package scope. The \"type\" field defines how .js and\nextensionless files should be treated within a particular package.json file’s\npackage scope. Every package in a project’s node_modules folder contains its\nown package.json file, so each project’s dependencies have their own package\nscopes. A package.json lacking a \"type\" field is treated as if it contained\n\"type\": \"commonjs\".

\n

The package scope applies not only to initial entry points (node my-app.js)\nbut also to files referenced by import statements and import() expressions.

\n
// my-app.js, in an ES module package scope because there is a package.json\n// file in the same folder with \"type\": \"module\".\n\nimport './startup/init.js';\n// Loaded as ES module since ./startup contains no package.json file,\n// and therefore inherits the ES module package scope from one level up.\n\nimport 'commonjs-package';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n\nimport './node_modules/commonjs-package/index.js';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n
\n

Files ending with .mjs are always loaded as ES modules regardless of package\nscope.

\n

Files ending with .cjs are always loaded as CommonJS regardless of package\nscope.

\n
import './legacy-file.cjs';\n// Loaded as CommonJS since .cjs is always loaded as CommonJS.\n\nimport 'commonjs-package/src/index.mjs';\n// Loaded as ES module since .mjs is always loaded as ES module.\n
\n

The .mjs and .cjs extensions may be used to mix types within the same\npackage scope:

\n", "type": "misc", "displayName": "Package Scope and File Extensions" }, { "textRaw": "`--input-type` flag", "name": "`--input-type`_flag", "desc": "

Strings passed in as an argument to --eval or --print (or -e or -p), or\npiped to node via STDIN, will be treated as ES modules when the\n--input-type=module flag is set.

\n
node --input-type=module --eval \"import { sep } from 'path'; console.log(sep);\"\n\necho \"import { sep } from 'path'; console.log(sep);\" | node --input-type=module\n
\n

For completeness there is also --input-type=commonjs, for explicitly running\nstring input as CommonJS. This is the default behavior if --input-type is\nunspecified.

", "type": "misc", "displayName": "`--input-type` flag" } ] }, { "textRaw": "Packages", "name": "packages", "modules": [ { "textRaw": "Package Entry Points", "name": "package_entry_points", "desc": "

There are two fields that can define entry points for a package: \"main\" and\n\"exports\". The \"main\" field is supported in all versions of Node.js, but its\ncapabilities are limited: it only defines the main entry point of the package.\nThe \"exports\" field, part of Package Exports, provides an alternative to\n\"main\" where the package main entry point can be defined while also\nencapsulating the package, preventing any other entry points besides those\ndefined in \"exports\". If package entry points are defined in both \"main\" and\n\"exports\", the latter takes precedence in versions of Node.js that support\n\"exports\". Conditional Exports can also be used within \"exports\" to\ndefine different package entry points per environment.

", "modules": [ { "textRaw": "`package.json` `\"main\"`", "name": "`package.json`_`\"main\"`", "desc": "

The package.json \"main\" field defines the entry point for a package,\nwhether the package is included into CommonJS via require or into an ES\nmodule via import.

\n\n
// ./node_modules/es-module-package/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./src/index.js\"\n}\n
\n
// ./my-app.mjs\n\nimport { something } from 'es-module-package';\n// Loads from ./node_modules/es-module-package/src/index.js\n
\n

An attempt to require the above es-module-package would attempt to load\n./node_modules/es-module-package/src/index.js as CommonJS, which would throw\nan error as Node.js would not be able to parse the export statement in\nCommonJS.

\n

As with import statements, for ES module usage the value of \"main\" must be\na full path including extension: \"./index.mjs\", not \"./index\".

\n

If the package.json \"type\" field is omitted, a .js file in \"main\" will\nbe interpreted as CommonJS.

\n

The \"main\" field can point to exactly one file, regardless of whether the\npackage is referenced via require (in a CommonJS context) or import (in an\nES module context).

", "type": "module", "displayName": "`package.json` `\"main\"`" }, { "textRaw": "Package Exports", "name": "package_exports", "desc": "

By default, all subpaths from a package can be imported (import 'pkg/x.js').\nCustom subpath aliasing and encapsulation can be provided through the\n\"exports\" field.

\n\n
// ./node_modules/es-module-package/package.json\n{\n  \"exports\": {\n    \"./submodule\": \"./src/submodule.js\"\n  }\n}\n
\n
import submodule from 'es-module-package/submodule';\n// Loads ./node_modules/es-module-package/src/submodule.js\n
\n

In addition to defining an alias, subpaths not defined by \"exports\" will\nthrow when an attempt is made to import them:

\n
import submodule from 'es-module-package/private-module.js';\n// Throws ERR_MODULE_NOT_FOUND\n
\n
\n

Note: this is not a strong encapsulation as any private modules can still be\nloaded by absolute paths.

\n
\n

Folders can also be mapped with package exports:

\n\n
// ./node_modules/es-module-package/package.json\n{\n  \"exports\": {\n    \"./features/\": \"./src/features/\"\n  }\n}\n
\n
import feature from 'es-module-package/features/x.js';\n// Loads ./node_modules/es-module-package/src/features/x.js\n
\n

If a package has no exports, setting \"exports\": false can be used instead of\n\"exports\": {} to indicate the package does not intend for submodules to be\nexposed.

\n

Any invalid exports entries will be ignored. This includes exports not\nstarting with \"./\" or a missing trailing \"/\" for directory exports.

\n

Array fallback support is provided for exports, similarly to import maps\nin order to be forwards-compatible with possible fallback workflows in future:

\n\n
{\n  \"exports\": {\n    \"./submodule\": [\"not:valid\", \"./submodule.js\"]\n  }\n}\n
\n

Since \"not:valid\" is not a supported target, \"./submodule.js\" is used\ninstead as the fallback, as if it were the only target.

\n

Defining a \".\" export will define the main entry point for the package,\nand will always take precedence over the \"main\" field in the package.json.

\n

This allows defining a different entry point for Node.js versions that support\nECMAScript modules and versions that don't, for example:

\n\n
{\n  \"main\": \"./main-legacy.cjs\",\n  \"exports\": {\n    \".\": \"./main-modern.cjs\"\n  }\n}\n
", "type": "module", "displayName": "Package Exports" }, { "textRaw": "Conditional Exports", "name": "conditional_exports", "desc": "

Conditional exports provide a way to map to different paths depending on\ncertain conditions. They are supported for both CommonJS and ES module imports.

\n

For example, a package that wants to provide different ES module exports for\nNode.js and the browser can be written:

\n\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.js\",\n  \"exports\": {\n    \"./feature\": {\n      \"import\": \"./feature-default.js\",\n      \"browser\": \"./feature-browser.js\"\n    }\n  }\n}\n
\n

When resolving the \".\" export, if no matching target is found, the \"main\"\nwill be used as the final fallback.

\n

The conditions supported in Node.js condition matching:

\n\n

Condition matching is applied in object order from first to last within the\n\"exports\" object.

\n

Using the \"require\" condition it is possible to define a package that will\nhave a different exported value for CommonJS and ES modules, which can be a\nhazard in that it can result in having two separate instances of the same\npackage in use in an application, which can cause a number of bugs.

\n

Other conditions such as \"browser\", \"electron\", \"deno\", \"react-native\",\netc. could be defined in other runtimes or tools. Condition names must not start\nwith \".\" or be numbers. Further restrictions, definitions or guidance on\ncondition names may be provided in future.

", "type": "module", "displayName": "Conditional Exports" }, { "textRaw": "Exports Sugar", "name": "exports_sugar", "desc": "

If the \".\" export is the only export, the \"exports\" field provides sugar\nfor this case being the direct \"exports\" field value.

\n

If the \".\" export has a fallback array or string value, then the \"exports\"\nfield can be set to this value directly.

\n\n
{\n  \"exports\": {\n    \".\": \"./main.js\"\n  }\n}\n
\n

can be written:

\n\n
{\n  \"exports\": \"./main.js\"\n}\n
\n

When using Conditional Exports, the rule is that all keys in the object\nmapping must not start with a \".\" otherwise they would be indistinguishable\nfrom exports subpaths.

\n\n
{\n  \"exports\": {\n    \".\": {\n      \"import\": \"./main.js\",\n      \"require\": \"./main.cjs\"\n    }\n  }\n}\n
\n

can be written:

\n\n
{\n  \"exports\": {\n    \"import\": \"./main.js\",\n    \"require\": \"./main.cjs\"\n  }\n}\n
\n

If writing any exports value that mixes up these two forms, an error will be\nthrown:

\n\n
{\n  // Throws on resolution!\n  \"exports\": {\n    \"./feature\": \"./lib/feature.js\",\n    \"import\": \"./main.js\",\n    \"require\": \"./main.cjs\"\n  }\n}\n
", "type": "module", "displayName": "Exports Sugar" } ], "type": "module", "displayName": "Package Entry Points" }, { "textRaw": "Dual CommonJS/ES Module Packages", "name": "dual_commonjs/es_module_packages", "desc": "

Prior to the introduction of support for ES modules in Node.js, it was a common\npattern for package authors to include both CommonJS and ES module JavaScript\nsources in their package, with package.json \"main\" specifying the CommonJS\nentry point and package.json \"module\" specifying the ES module entry point.\nThis enabled Node.js to run the CommonJS entry point while build tools such as\nbundlers used the ES module entry point, since Node.js ignored (and still\nignores) the top-level \"module\" field.

\n

Node.js can now run ES module entry points, and a package can contain both\nCommonJS and ES module entry points (either via separate specifiers such as\n'pkg' and 'pkg/es-module', or both at the same specifier via Conditional\nExports). Unlike in the scenario where \"module\" is only used by bundlers,\nor ES module files are transpiled into CommonJS on the fly before evaluation by\nNode.js, the files referenced by the ES module entry point are evaluated as ES\nmodules.

", "modules": [ { "textRaw": "Dual Package Hazard", "name": "dual_package_hazard", "desc": "

When an application is using a package that provides both CommonJS and ES module\nsources, there is a risk of certain bugs if both versions of the package get\nloaded. This potential comes from the fact that the pkgInstance created by\nconst pkgInstance = require('pkg') is not the same as the pkgInstance\ncreated by import pkgInstance from 'pkg' (or an alternative main path like\n'pkg/module'). This is the “dual package hazard,” where two versions of the\nsame package can be loaded within the same runtime environment. While it is\nunlikely that an application or package would intentionally load both versions\ndirectly, it is common for an application to load one version while a dependency\nof the application loads the other version. This hazard can happen because\nNode.js supports intermixing CommonJS and ES modules, and can lead to unexpected\nbehavior.

\n

If the package main export is a constructor, an instanceof comparison of\ninstances created by the two versions returns false, and if the export is an\nobject, properties added to one (like pkgInstance.foo = 3) are not present on\nthe other. This differs from how import and require statements work in\nall-CommonJS or all-ES module environments, respectively, and therefore is\nsurprising to users. It also differs from the behavior users are familiar with\nwhen using transpilation via tools like Babel or esm.

", "type": "module", "displayName": "Dual Package Hazard" }, { "textRaw": "Writing Dual Packages While Avoiding or Minimizing Hazards", "name": "writing_dual_packages_while_avoiding_or_minimizing_hazards", "desc": "

First, the hazard described in the previous section occurs when a package\ncontains both CommonJS and ES module sources and both sources are provided for\nuse in Node.js, either via separate main entry points or exported paths. A\npackage could instead be written where any version of Node.js receives only\nCommonJS sources, and any separate ES module sources the package may contain\ncould be intended only for other environments such as browsers. Such a package\nwould be usable by any version of Node.js, since import can refer to CommonJS\nfiles; but it would not provide any of the advantages of using ES module syntax.

\n

A package could also switch from CommonJS to ES module syntax in a breaking\nchange version bump. This has the obvious disadvantage that the newest version\nof the package would only be usable in ES module-supporting versions of Node.js.

\n

Every pattern has tradeoffs, but there are two broad approaches that satisfy the\nfollowing conditions:

\n
    \n
  1. The package is usable via both require and import.
  2. \n
  3. The package is usable in both current Node.js and older versions of Node.js\nthat lack support for ES modules.
  4. \n
  5. The package main entry point, e.g. 'pkg' can be used by both require to\nresolve to a CommonJS file and by import to resolve to an ES module file.\n(And likewise for exported paths, e.g. 'pkg/feature'.)
  6. \n
  7. The package provides named exports, e.g. import { name } from 'pkg' rather\nthan import pkg from 'pkg'; pkg.name.
  8. \n
  9. The package is potentially usable in other ES module environments such as\nbrowsers.
  10. \n
  11. The hazards described in the previous section are avoided or minimized.
  12. \n
", "modules": [ { "textRaw": "Approach #1: Use an ES Module Wrapper", "name": "approach_#1:_use_an_es_module_wrapper", "desc": "

Write the package in CommonJS or transpile ES module sources into CommonJS, and\ncreate an ES module wrapper file that defines the named exports. Using\nConditional Exports, the ES module wrapper is used for import and the\nCommonJS entry point for require.

\n\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \"require\": \"./index.cjs\",\n    \"import\": \"./wrapper.mjs\"\n  }\n}\n
\n
// ./node_modules/pkg/index.cjs\nexports.name = 'value';\n
\n
// ./node_modules/pkg/wrapper.mjs\nimport cjsModule from './index.cjs';\nexport const name = cjsModule.name;\n
\n

In this example, the name from import { name } from 'pkg' is the same\nsingleton as the name from const { name } = require('pkg'). Therefore ===\nreturns true when comparing the two names and the divergent specifier hazard\nis avoided.

\n

If the module is not simply a list of named exports, but rather contains a\nunique function or object export like module.exports = function () { ... },\nor if support in the wrapper for the import pkg from 'pkg' pattern is desired,\nthen the wrapper would instead be written to export the default optionally\nalong with any named exports as well:

\n
import cjsModule from './index.cjs';\nexport const name = cjsModule.name;\nexport default cjsModule;\n
\n

This approach is appropriate for any of the following use cases:

\n\n

A variant of this approach not requiring conditional exports for consumers could\nbe to add an export, e.g. \"./module\", to point to an all-ES module-syntax\nversion of the package. This could be used via import 'pkg/module' by users\nwho are certain that the CommonJS version will not be loaded anywhere in the\napplication, such as by dependencies; or if the CommonJS version can be loaded\nbut doesn’t affect the ES module version (for example, because the package is\nstateless):

\n\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \".\": \"./index.cjs\",\n    \"./module\": \"./wrapper.mjs\"\n  }\n}\n
", "type": "module", "displayName": "Approach #1: Use an ES Module Wrapper" }, { "textRaw": "Approach #2: Isolate State", "name": "approach_#2:_isolate_state", "desc": "

The most straightforward package.json would be one that defines the separate\nCommonJS and ES module entry points directly:

\n\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \"import\": \"./index.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n
\n

This can be done if both the CommonJS and ES module versions of the package are\nequivalent, for example because one is the transpiled output of the other; and\nthe package’s management of state is carefully isolated (or the package is\nstateless).

\n

The reason that state is an issue is because both the CommonJS and ES module\nversions of the package may get used within an application; for example, the\nuser’s application code could import the ES module version while a dependency\nrequires the CommonJS version. If that were to occur, two copies of the\npackage would be loaded in memory and therefore two separate states would be\npresent. This would likely cause hard-to-troubleshoot bugs.

\n

Aside from writing a stateless package (if JavaScript’s Math were a package,\nfor example, it would be stateless as all of its methods are static), there are\nsome ways to isolate state so that it’s shared between the potentially loaded\nCommonJS and ES module instances of the package:

\n
    \n
  1. \n

    If possible, contain all state within an instantiated object. JavaScript’s\nDate, for example, needs to be instantiated to contain state; if it were a\npackage, it would be used like this:

    \n
    import Date from 'date';\nconst someDate = new Date();\n// someDate contains state; Date does not\n
    \n

    The new keyword isn’t required; a package’s function can return a new\nobject, or modify a passed-in object, to keep the state external to the\npackage.

    \n
  2. \n
  3. \n

    Isolate the state in one or more CommonJS files that are shared between the\nCommonJS and ES module versions of the package. For example, if the CommonJS\nand ES module entry points are index.cjs and index.mjs, respectively:

    \n
    // ./node_modules/pkg/index.cjs\nconst state = require('./state.cjs');\nmodule.exports.state = state;\n
    \n
    // ./node_modules/pkg/index.mjs\nimport state from './state.cjs';\nexport {\n  state\n};\n
    \n

    Even if pkg is used via both require and import in an application (for\nexample, via import in application code and via require by a dependency)\neach reference of pkg will contain the same state; and modifying that\nstate from either module system will apply to both.

    \n
  4. \n
\n

Any plugins that attach to the package’s singleton would need to separately\nattach to both the CommonJS and ES module singletons.

\n

This approach is appropriate for any of the following use cases:

\n\n

Even with isolated state, there is still the cost of possible extra code\nexecution between the CommonJS and ES module versions of a package.

\n

As with the previous approach, a variant of this approach not requiring\nconditional exports for consumers could be to add an export, e.g.\n\"./module\", to point to an all-ES module-syntax version of the package:

\n\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \".\": \"./index.cjs\",\n    \"./module\": \"./index.mjs\"\n  }\n}\n
", "type": "module", "displayName": "Approach #2: Isolate State" } ], "type": "module", "displayName": "Writing Dual Packages While Avoiding or Minimizing Hazards" } ], "type": "module", "displayName": "Dual CommonJS/ES Module 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 four types of specifiers:

\n\n

Bare specifiers, and the bare specifier portion of deep import specifiers, are\nstrings; but everything else in a specifier is a URL.

\n

Only file: and data: URLs are supported. A specifier like\n'https://example.com/app.js' may be supported by browsers but it is not\nsupported in Node.js.

\n

Specifiers may not begin with / or //. These are reserved for potential\nfuture use. The root of the current volume may be referenced via file:///.

", "modules": [ { "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 will not work because data: is not a\nspecial scheme. For example, attempting to load ./foo\nfrom data:text/javascript,import \"./foo\"; will fail to resolve since there\nis no concept of relative resolution for data: URLs. An example of a data:\nURLs being used is:

\n
import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"';\n
", "type": "module", "displayName": "`data:` Imports" } ], "type": "module", "displayName": "Terminology" } ], "type": "misc", "displayName": "`import` Specifiers" }, { "textRaw": "Differences Between ES Modules and CommonJS", "name": "differences_between_es_modules_and_commonjs", "modules": [ { "textRaw": "Mandatory file extensions", "name": "mandatory_file_extensions", "desc": "

A file extension must be provided when using the import keyword. Directory\nindexes (e.g. './startup/index.js') must also be fully specified.

\n

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

", "type": "module", "displayName": "Mandatory file extensions" }, { "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`, `exports`, `module.exports`, `__filename`, `__dirname`", "name": "no_`require`,_`exports`,_`module.exports`,_`__filename`,_`__dirname`", "desc": "

These CommonJS variables are not available in ES modules.

\n

require can be imported into an ES module using module.createRequire().

\n

Equivalents of __filename and __dirname can be created inside of each file\nvia import.meta.url.

\n
import { fileURLToPath } from 'url';\nimport { dirname } from 'path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n
", "type": "module", "displayName": "No `require`, `exports`, `module.exports`, `__filename`, `__dirname`" }, { "textRaw": "No `require.extensions`", "name": "no_`require.extensions`", "desc": "

require.extensions is not used by import. The expectation is that loader\nhooks can provide this workflow in the future.

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

require.cache is not used by import. It has a separate cache.

", "type": "module", "displayName": "No `require.cache`" }, { "textRaw": "URL-based paths", "name": "url-based_paths", "desc": "

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

\n

Modules will be loaded multiple times if the import specifier used to resolve\nthem have 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

For now, only modules using the file: protocol can be loaded.

", "type": "module", "displayName": "URL-based paths" } ], "type": "misc", "displayName": "Differences Between ES Modules and CommonJS" }, { "textRaw": "Interoperability with CommonJS", "name": "interoperability_with_commonjs", "modules": [ { "textRaw": "`require`", "name": "`require`", "desc": "

require always treats the files it references as CommonJS. This applies\nwhether require is used the traditional way within a CommonJS environment, or\nin an ES module environment using module.createRequire().

\n

To include an ES module into CommonJS, use import().

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

An import statement can reference an ES module or a CommonJS module. Other\nfile types such as JSON or Native modules are not supported. For those, use\nmodule.createRequire().

\n

import statements are permitted only in ES modules. For similar functionality\nin CommonJS, see import().

\n

The specifier of an import statement (the string after the from keyword)\ncan either be an URL-style relative path like './file.mjs' or a package name\nlike 'fs'.

\n

Like in CommonJS, files within packages can be accessed by appending a path to\nthe package name; unless the package’s package.json contains an \"exports\"\nfield, in which case files within packages need to be accessed via the path\ndefined in \"exports\".

\n
import { sin, cos } from 'geometry/trigonometry-functions.mjs';\n
\n

Only the “default export” is supported for CommonJS files or packages:

\n\n
import packageMain from 'commonjs-package'; // Works\n\nimport { method } from 'commonjs-package'; // Errors\n
", "type": "module", "displayName": "`import` statements" }, { "textRaw": "`import()` expressions", "name": "`import()`_expressions", "desc": "

Dynamic import() is supported in both CommonJS and ES modules. It can be used\nto include ES module files from CommonJS code.

\n
(async () => {\n  await import('./my-app.mjs');\n})();\n
", "type": "module", "displayName": "`import()` expressions" } ], "type": "misc", "displayName": "Interoperability with CommonJS" }, { "textRaw": "CommonJS, JSON, and Native Modules", "name": "commonjs,_json,_and_native_modules", "desc": "

CommonJS, JSON, and Native modules can be used with\nmodule.createRequire().

\n
// cjs.cjs\nmodule.exports = 'cjs';\n\n// esm.mjs\nimport { createRequire } from 'module';\n\nconst require = createRequire(import.meta.url);\n\nconst cjs = require('./cjs.cjs');\ncjs === 'cjs'; // true\n
", "type": "misc", "displayName": "CommonJS, JSON, and Native Modules" }, { "textRaw": "Builtin modules", "name": "builtin_modules", "desc": "

Builtin modules will provide named exports of their public API. 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';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;\n
", "type": "misc", "displayName": "Builtin modules" }, { "textRaw": "Experimental JSON Modules", "name": "experimental_json_modules", "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 will 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 will be 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
", "type": "misc", "displayName": "Experimental JSON Modules" }, { "textRaw": "Experimental Wasm Modules", "name": "experimental_wasm_modules", "desc": "

Importing Web Assembly modules is supported under the\n--experimental-wasm-modules flag, allowing any .wasm files to be\nimported as normal modules while also supporting their module imports.

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

", "type": "misc", "displayName": "Experimental Wasm Modules" }, { "textRaw": "Experimental Loaders", "name": "Experimental Loaders", "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", "modules": [ { "textRaw": "resolve hook", "name": "resolve_hook", "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

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
/**\n * @param {string} specifier\n * @param {object} context\n * @param {string} context.parentURL\n * @param {function} defaultResolve\n * @returns {object} response\n * @returns {string} response.url\n */\nexport async function resolve(specifier, context, defaultResolve) {\n  const { parentURL = null } = context;\n  if (someCondition) {\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 : new URL(specifier).href\n    };\n  }\n  // Defer to Node.js for all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n
", "type": "module", "displayName": "resolve hook" }, { "textRaw": "getFormat hook", "name": "getformat_hook", "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

The getFormat hook provides a way to define a custom method of determining how\na URL should be interpreted. This can be one of 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
formatDescription
'builtin'Load a Node.js builtin module
'commonjs'Load a Node.js CommonJS module
'dynamic'Use a dynamic instantiate hook
'json'Load a JSON file
'module'Load a standard JavaScript module (ES module)
'wasm'Load a WebAssembly module
\n
/**\n * @param {string} url\n * @param {object} context (currently empty)\n * @param {function} defaultGetFormat\n * @returns {object} response\n * @returns {string} response.format\n */\nexport async function getFormat(url, context, defaultGetFormat) {\n  if (someCondition) {\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 table above.\n    return {\n      format: 'module'\n    };\n  }\n  // Defer to Node.js for all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n
", "type": "module", "displayName": "getFormat hook" }, { "textRaw": "getSource hook", "name": "getsource_hook", "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

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 {object} context\n * @param {string} context.format\n * @param {function} defaultGetSource\n * @returns {object} response\n * @returns {string|buffer} response.source\n */\nexport async function getSource(url, context, defaultGetSource) {\n  const { format } = context;\n  if (someCondition) {\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
", "type": "module", "displayName": "getSource hook" }, { "textRaw": "transformSource hook", "name": "transformsource_hook", "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

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|buffer} source\n * @param {object} context\n * @param {string} context.url\n * @param {string} context.format\n * @param {function} defaultTransformSource\n * @returns {object} response\n * @returns {string|buffer} response.source\n */\nexport async function transformSource(source,\n                                      context,\n                                      defaultTransformSource) {\n  const { url, format } = context;\n  if (someCondition) {\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(\n    source, context, defaultTransformSource);\n}\n
", "type": "module", "displayName": "transformSource hook" }, { "textRaw": "dynamicInstantiate hook", "name": "dynamicinstantiate_hook", "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

To create a custom dynamic module that doesn't correspond to one of the\nexisting format interpretations, the dynamicInstantiate hook can be used.\nThis hook is called only for modules that return format: 'dynamic' from\nthe getFormat hook.

\n
/**\n * @param {string} url\n * @returns {object} response\n * @returns {array} response.exports\n * @returns {function} response.execute\n */\nexport async function dynamicInstantiate(url) {\n  return {\n    exports: ['customExportName'],\n    execute: (exports) => {\n      // Get and set functions provided for pre-allocated export names\n      exports.customExportName.set('value');\n    }\n  };\n}\n
\n

With the list of module exports provided upfront, the execute function will\nthen be called at the exact point of module evaluation order for that module\nin the import tree.

\n

Examples

\n

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

", "type": "module", "displayName": "dynamicInstantiate hook" }, { "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 this loader, running:

\n
node --experimental-loader ./https-loader.mjs ./main.js\n
\n

Will print 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 obviously 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';\n\nconst baseURL = pathToFileURL(`${process.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 this loader, running:

\n
node --experimental-loader ./coffeescript-loader.mjs main.coffee\n
\n

Will cause 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, in addition to the unique module\nformat for that resolved URL given by the ESM_FORMAT routine.

\n

The \"module\" format is returned for an ECMAScript Module, while the\n\"commonjs\" format is used to indicate loading through the legacy\nCommonJS loader. Additional formats such as \"addon\" can be extended in future\nupdates.

\n

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

\n

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

\n
\nResolver algorithm specification\n

ESM_RESOLVE(specifier, parentURL)

\n
\n
    \n
  1. Let resolvedURL be undefined.
  2. \n
  3. \n

    If specifier is a valid URL, then

    \n
      \n
    1. Set resolvedURL to the result of parsing and reserializing\nspecifier as a URL.
    2. \n
    \n
  4. \n
  5. \n

    Otherwise, if specifier starts with \"/\", then

    \n
      \n
    1. Throw an Invalid Specifier error.
    2. \n
    \n
  6. \n
  7. \n

    Otherwise, if specifier starts with \"./\" or \"../\", then

    \n
      \n
    1. Set resolvedURL to the URL resolution of specifier relative to\nparentURL.
    2. \n
    \n
  8. \n
  9. \n

    Otherwise,

    \n
      \n
    1. Note: specifier is now a bare specifier.
    2. \n
    3. Set resolvedURL the result of\nPACKAGE_RESOLVE(specifier, parentURL).
    4. \n
    \n
  10. \n
  11. \n

    If resolvedURL contains any percent encodings of \"/\" or \"\\\" (\"%2f\"\nand \"%5C\" respectively), then

    \n
      \n
    1. Throw an Invalid Specifier error.
    2. \n
    \n
  12. \n
  13. \n

    If the file at resolvedURL does not exist, then

    \n
      \n
    1. Throw a Module Not Found error.
    2. \n
    \n
  14. \n
  15. Set resolvedURL to the real path of resolvedURL.
  16. \n
  17. Let format be the result of ESM_FORMAT(resolvedURL).
  18. \n
  19. Load resolvedURL as module format, format.
  20. \n
\n
\n

PACKAGE_RESOLVE(packageSpecifier, parentURL)

\n
\n
    \n
  1. Let packageName be undefined.
  2. \n
  3. Let packageSubpath be undefined.
  4. \n
  5. \n

    If packageSpecifier is an empty string, then

    \n
      \n
    1. Throw an Invalid Specifier error.
    2. \n
    \n
  6. \n
  7. \n

    Otherwise,

    \n
      \n
    1. \n

      If packageSpecifier does not contain a \"/\" separator, then

      \n
        \n
      1. Throw an Invalid 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. \n

    If packageName starts with \".\" or contains \"\\\" or \"%\", then

    \n
      \n
    1. Throw an Invalid Specifier error.
    2. \n
    \n
  10. \n
  11. Let packageSubpath be undefined.
  12. \n
  13. \n

    If the length of packageSpecifier is greater than the length of\npackageName, then

    \n
      \n
    1. Set packageSubpath to \".\" concatenated with the substring of\npackageSpecifier from the position at the length of packageName.
    2. \n
    \n
  14. \n
  15. \n

    If packageSubpath contains any \".\" or \"..\" segments or percent\nencoded strings for \"/\" or \"\\\", then

    \n
      \n
    1. Throw an Invalid Specifier error.
    2. \n
    \n
  16. \n
  17. Set selfUrl to the result of\nSELF_REFERENCE_RESOLVE(packageName, packageSubpath, parentURL).
  18. \n
  19. If selfUrl isn't empty, return selfUrl.
  20. \n
  21. \n

    If packageSubpath is undefined and packageName is a Node.js builtin\nmodule, then

    \n
      \n
    1. Return the string \"node:\" concatenated with packageSpecifier.
    2. \n
    \n
  22. \n
  23. \n

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

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

      If packageSubpath is _undefined__, then

      \n
        \n
      1. Return the result of PACKAGE_MAIN_RESOLVE(packageURL,\npjson).
      2. \n
      \n
    10. \n
    11. \n

      Otherwise,

      \n
        \n
      1. \n

        If pjson is not null and pjson has an \"exports\" key, then

        \n
          \n
        1. Let exports be pjson.exports.
        2. \n
        3. \n

          If exports is not null or undefined, then

          \n
            \n
          1. Return PACKAGE_EXPORTS_RESOLVE(packageURL,\npackageSubpath, pjson.exports).
          2. \n
          \n
        4. \n
        \n
      2. \n
      3. Return the URL resolution of packageSubpath in packageURL.
      4. \n
      \n
    12. \n
    \n
  24. \n
  25. Throw a Module Not Found error.
  26. \n
\n
\n

SELF_REFERENCE_RESOLVE(packageName, packageSubpath, parentURL)

\n
\n
    \n
  1. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
  2. \n
  3. \n

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

    If pjson does not include an \"exports\" property, then

    \n
      \n
    1. Return undefined.
    2. \n
    \n
  8. \n
  9. \n

    If pjson.name is equal to packageName, then

    \n
      \n
    1. \n

      If packageSubpath is undefined, then

      \n
        \n
      1. Return the result of PACKAGE_MAIN_RESOLVE(packageURL, pjson).
      2. \n
      \n
    2. \n
    3. \n

      Otherwise,

      \n
        \n
      1. \n

        If pjson is not null and pjson has an \"exports\" key, then

        \n
          \n
        1. Let exports be pjson.exports.
        2. \n
        3. \n

          If exports is not null or undefined, then

          \n
            \n
          1. Return PACKAGE_EXPORTS_RESOLVE(packageURL, subpath,\npjson.exports).
          2. \n
          \n
        4. \n
        \n
      2. \n
      3. Return the URL resolution of subpath in packageURL.
      4. \n
      \n
    4. \n
    \n
  10. \n
  11. Otherwise, return undefined.
  12. \n
\n
\n

PACKAGE_MAIN_RESOLVE(packageURL, pjson)

\n
\n
    \n
  1. \n

    If pjson is null, then

    \n
      \n
    1. Throw a Module Not Found error.
    2. \n
    \n
  2. \n
  3. \n

    If pjson.exports is not null or undefined, then

    \n
      \n
    1. If exports is an Object with both a key starting with \".\" and a key\nnot starting with \".\", throw an \"Invalid Package Configuration\" error.
    2. \n
    3. \n

      If pjson.exports is a String or Array, or an Object containing no\nkeys starting with \".\", then

      \n
        \n
      1. Return PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL,\npjson.exports, \"\").
      2. \n
      \n
    4. \n
    5. \n

      If pjson.exports is an Object containing a \".\" property, then

      \n
        \n
      1. Let mainExport be the \".\" property in pjson.exports.
      2. \n
      3. Return PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL,\nmainExport, \"\").
      4. \n
      \n
    6. \n
    \n
  4. \n
  5. \n

    If pjson.main is a String, then

    \n
      \n
    1. Let resolvedMain be the URL resolution of packageURL, \"/\", and\npjson.main.
    2. \n
    3. \n

      If the file at resolvedMain exists, then

      \n
        \n
      1. Return resolvedMain.
      2. \n
      \n
    4. \n
    \n
  6. \n
  7. \n

    If pjson.type is equal to \"module\", then

    \n
      \n
    1. Throw a Module Not Found error.
    2. \n
    \n
  8. \n
  9. Let legacyMainURL be the result applying the legacy\nLOAD_AS_DIRECTORY CommonJS resolver to packageURL, throwing a\nModule Not Found error for no resolution.
  10. \n
  11. Return legacyMainURL.
  12. \n
\n
\n

PACKAGE_EXPORTS_RESOLVE(packageURL, packagePath, exports)

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

    If exports is an Object and all keys of exports start with \".\", then

    \n
      \n
    1. Set packagePath to \"./\" concatenated with packagePath.
    2. \n
    3. \n

      If packagePath is a key of exports, then

      \n
        \n
      1. Let target be the value of exports[packagePath].
      2. \n
      3. Return PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, target,\n\"\", defaultEnv).
      4. \n
      \n
    4. \n
    5. Let directoryKeys be the list of keys of exports ending in\n\"/\", sorted by length descending.
    6. \n
    7. \n

      For each key directory in directoryKeys, do

      \n
        \n
      1. \n

        If packagePath starts with directory, then

        \n
          \n
        1. Let target be the value of exports[directory].
        2. \n
        3. Let subpath be the substring of target starting at the index\nof the length of directory.
        4. \n
        5. Return PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, target,\nsubpath, defaultEnv).
        6. \n
        \n
      2. \n
      \n
    8. \n
    \n
  4. \n
  5. Throw a Module Not Found error.
  6. \n
\n
\n

PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, target, subpath, env)

\n
\n
    \n
  1. \n

    If target is a String, then

    \n
      \n
    1. If target does not start with \"./\", throw a Module Not Found\nerror.
    2. \n
    3. If subpath has non-zero length and target does not end with \"/\",\nthrow a Module Not Found error.
    4. \n
    5. If target or subpath contain any \"node_modules\" segments including\n\"node_modules\" percent-encoding, throw a Module Not Found error.
    6. \n
    7. Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
    8. \n
    9. \n

      If resolvedTarget is contained in packageURL, then

      \n
        \n
      1. Let resolved be the URL resolution of the concatenation of\nsubpath and resolvedTarget.
      2. \n
      3. \n

        If resolved is contained in resolvedTarget, then

        \n
          \n
        1. Return resolved.
        2. \n
        \n
      4. \n
      \n
    10. \n
    \n
  2. \n
  3. \n

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

      For each property p of target, in object insertion order as,

      \n
        \n
      1. \n

        If env contains an entry for p, then

        \n
          \n
        1. Let targetValue be the value of the p property in target.
        2. \n
        3. Let resolved be the result of PACKAGE_EXPORTS_TARGET_RESOLVE\n(packageURL, targetValue, subpath, env).
        4. \n
        5. Assert: resolved is a String.
        6. \n
        7. Return resolved.
        8. \n
        \n
      2. \n
      \n
    4. \n
    \n
  4. \n
  5. \n

    Otherwise, if target is an Array, then

    \n
      \n
    1. \n

      For each item targetValue in target, do

      \n
        \n
      1. If targetValue is an Array, continue the loop.
      2. \n
      3. Let resolved be the result of\nPACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, targetValue,\nsubpath, env), continuing the loop on abrupt completion.
      4. \n
      5. Assert: resolved is a String.
      6. \n
      7. Return resolved.
      8. \n
      \n
    2. \n
    \n
  6. \n
  7. Throw a Module Not Found error.
  8. \n
\n
\n

ESM_FORMAT(url)

\n
\n
    \n
  1. Assert: url corresponds to an existing file pathname.
  2. \n
  3. Let pjson be the result of READ_PACKAGE_SCOPE(url).
  4. \n
  5. \n

    If url ends in \".mjs\", then

    \n
      \n
    1. Return \"module\".
    2. \n
    \n
  6. \n
  7. \n

    If url ends in \".cjs\", then

    \n
      \n
    1. Return \"commonjs\".
    2. \n
    \n
  8. \n
  9. \n

    If pjson?.type exists and is \"module\", then

    \n
      \n
    1. \n

      If url ends in \".js\" or lacks a file extension, then

      \n
        \n
      1. Return \"module\".
      2. \n
      \n
    2. \n
    3. Throw an Unsupported File Extension error.
    4. \n
    \n
  10. \n
  11. \n

    Otherwise,

    \n
      \n
    1. \n

      If url lacks a file extension, then

      \n
        \n
      1. Return \"commonjs\".
      2. \n
      \n
    2. \n
    3. Throw an Unsupported File Extension error.
    4. \n
    \n
  12. \n
\n
\n

READ_PACKAGE_SCOPE(url)

\n
\n
    \n
  1. Let scopeURL be url.
  2. \n
  3. \n

    While scopeURL is not the file system root,

    \n
      \n
    1. If scopeURL ends in a \"node_modules\" path segment, return null.
    2. \n
    3. Let pjson be the result of READ_PACKAGE_JSON(scopeURL).
    4. \n
    5. \n

      If pjson is not null, then

      \n
        \n
      1. Return pjson.
      2. \n
      \n
    6. \n
    7. Set scopeURL to the parent URL of scopeURL.
    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. \n

    If the file at pjsonURL does not exist, then

    \n
      \n
    1. Return null.
    2. \n
    \n
  4. \n
  5. \n

    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
\n
", "type": "module", "displayName": "Resolver Algorithm" }, { "textRaw": "Customizing ESM specifier resolution algorithm", "name": "customizing_esm_specifier_resolution_algorithm", "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
", "type": "module", "displayName": "Customizing ESM specifier resolution algorithm" } ], "type": "misc", "displayName": "Resolution Algorithm" } ], "properties": [ { "textRaw": "`meta` {Object}", "type": "Object", "name": "meta", "desc": "

The import.meta metaproperty is an Object that contains the following\nproperty:

\n" } ] } ] }