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

The --experimental-modules flag can be used to enable support for\nECMAScript modules (ES modules).

\n

Once enabled, Node.js will treat the following as ES modules when passed to\nnode as the initial input, or when referenced by import statements within\nES module code:

\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 .mjs, or lacking any extension,\nwill be loaded as ES modules when the nearest parent package.json file\ncontains a top-level field \"type\" with a value of \"module\".

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

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

", "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 --experimental-modules my-app.js) but also to files referenced by import\nstatements 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 --experimental-modules --input-type=module --eval \\\n  \"import { sep } from 'path'; console.log(sep);\"\n\necho \"import { sep } from 'path'; console.log(sep);\" | \\\n  node --experimental-modules --input-type=module\n
\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": "

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

", "modules": [ { "textRaw": "Compatibility with CommonJS-Only Versions of Node.js", "name": "compatibility_with_commonjs-only_versions_of_node.js", "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) \"module\".

\n

Node.js can now run ES module entry points, but it remains impossible for a\npackage to define separate CommonJS and ES module entry points. This is for good\nreason: the pkg variable created from import pkg from 'pkg' is not the same\nsingleton as the pkg variable created from const pkg = require('pkg'), so if\nboth are referenced within the same app (including dependencies), unexpected\nbehavior might occur.

\n

There are two general approaches to addressing this limitation while still\npublishing a package that contains both CommonJS and ES module sources:

\n
    \n
  1. \n

    Document a new ES module entry point that’s not the package \"main\", e.g.\nimport pkg from 'pkg/module.mjs' (or import 'pkg/esm', if using package\nexports). The package \"main\" would still point to a CommonJS file, and\nthus the package would remain compatible with older versions of Node.js that\nlack support for ES modules.

    \n
  2. \n
  3. \n

    Switch the package \"main\" entry point to an ES module file as part of a\nbreaking change version bump. This version and above would only be usable on\nES module-supporting versions of Node.js. If the package still contains a\nCommonJS version, it would be accessible via a path within the package, e.g.\nrequire('pkg/commonjs'); this is essentially the inverse of the previous\napproach. Package consumers who are using CommonJS-only versions of Node.js\nwould need to update their code from require('pkg') to e.g.\nrequire('pkg/commonjs').

    \n
  4. \n
\n

Of course, a package could also include only CommonJS or only ES module sources.\nAn existing package could make a semver major bump to an ES module-only version,\nthat would only be supported in ES module-supporting versions of Node.js (and\nother runtimes). New packages could be published containing only ES module\nsources, and would be compatible only with ES module-supporting runtimes.

", "type": "module", "displayName": "Compatibility with CommonJS-Only Versions of Node.js" } ], "type": "module", "displayName": "Package Entry Points" }, { "textRaw": "Package Exports", "name": "package_exports", "desc": "

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

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

Exports can also be used to map the main entry point of a package:

\n\n
// ./node_modules/es-module-package/package.json\n{\n  \"exports\": {\n    \".\": \"./main.js\"\n  }\n}\n
\n

where the \".\" indicates loading the package without any subpath. Exports will\nalways override any existing \"main\" value for both CommonJS and\nES module packages.

\n

For packages with only a main entry point, an \"exports\" value of just\na string is also supported:

\n\n
// ./node_modules/es-module-package/package.json\n{\n  \"exports\": \"./main.js\"\n}\n
\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 forward-compatible with 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.

", "type": "module", "displayName": "Package Exports" } ], "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, a CommonJS module, or JSON.\nOther file types such as Native modules are not supported. For those,\nuse module.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.

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

Currently only the “default export” is supported for CommonJS files or\npackages:

\n\n
import packageMain from 'commonjs-package'; // Works\n\nimport { method } from 'commonjs-package'; // Errors\n
\n

There are ongoing efforts to make the latter code possible.

\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.js\nmodule.exports = 'cjs';\n\n// esm.mjs\nimport { createRequire } from 'module';\nimport { fileURLToPath as fromURL } from 'url';\n\nconst require = createRequire(fromURL(import.meta.url));\n\nconst cjs = require('./cjs');\ncjs === 'cjs'; // true\n
", "type": "misc", "displayName": "CommonJS, JSON, and Native Modules" }, { "textRaw": "Builtin modules", "name": "builtin_modules", "desc": "

Builtin modules will provide named exports of their public API, as well as a\ndefault export which can be used for, among other things, modifying the named\nexports. Named exports of builtin modules are updated when the corresponding\nexports property is accessed, redefined, or deleted.

\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';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\n\nfs.readFileSync === readFileSync;\n
", "type": "misc", "displayName": "Builtin modules" }, { "textRaw": "JSON Modules", "name": "json_modules", "desc": "

JSON modules follow the WHATWG JSON modules specification.

\n

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
", "type": "misc", "displayName": "JSON Modules" }, { "textRaw": "Experimental Wasm Modules", "name": "experimental_wasm_modules", "desc": "

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

\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-modules --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 Loader hooks", "name": "Experimental Loader hooks", "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": "Resolve hook", "name": "resolve_hook", "desc": "

The resolve hook returns the resolved file URL and module format for a\ngiven module specifier and parent file URL:

\n
import { URL, pathToFileURL } from 'url';\nconst baseURL = pathToFileURL(process.cwd()).href;\n\n/**\n * @param {string} specifier\n * @param {string} parentModuleURL\n * @param {function} defaultResolver\n */\nexport async function resolve(specifier,\n                              parentModuleURL = baseURL,\n                              defaultResolver) {\n  return {\n    url: new URL(specifier, parentModuleURL).href,\n    format: 'module'\n  };\n}\n
\n

The parentModuleURL is provided as undefined when performing main Node.js\nload itself.

\n

The default Node.js ES module resolution function is provided as a third\nargument to the resolver for easy compatibility workflows.

\n

In addition to returning the resolved file URL value, the resolve hook also\nreturns a format property specifying the module format of the resolved\nmodule. This can be one of the following:

\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
'wasm'Load a WebAssembly module
\n

For example, a dummy loader to load JavaScript restricted to browser resolution\nrules with only JS file extension and Node.js builtin modules support could\nbe written:

\n
import path from 'path';\nimport process from 'process';\nimport Module from 'module';\nimport { URL, pathToFileURL } from 'url';\n\nconst builtins = Module.builtinModules;\nconst JS_EXTENSIONS = new Set(['.js', '.mjs']);\n\nconst baseURL = pathToFileURL(process.cwd()).href;\n\n/**\n * @param {string} specifier\n * @param {string} parentModuleURL\n * @param {function} defaultResolver\n */\nexport async function resolve(specifier,\n                              parentModuleURL = baseURL,\n                              defaultResolver) {\n  if (builtins.includes(specifier)) {\n    return {\n      url: specifier,\n      format: 'builtin'\n    };\n  }\n  if (/^\\.{0,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) {\n    // For node_modules support:\n    // return defaultResolver(specifier, parentModuleURL);\n    throw new Error(\n      `imports must begin with '/', './', or '../'; '${specifier}' does not`);\n  }\n  const resolved = new URL(specifier, parentModuleURL);\n  const ext = path.extname(resolved.pathname);\n  if (!JS_EXTENSIONS.has(ext)) {\n    throw new Error(\n      `Cannot load file with non-JavaScript file extension ${ext}.`);\n  }\n  return {\n    url: resolved.href,\n    format: 'module'\n  };\n}\n
\n

With this loader, running:

\n
NODE_OPTIONS='--experimental-modules --experimental-loader ./custom-loader.mjs' node x.js\n
\n

would load the module x.js as an ES module with relative resolution support\n(with node_modules loading skipped in this example).

", "type": "misc", "displayName": "Resolve hook" }, { "textRaw": "Dynamic instantiate hook", "name": "dynamic_instantiate_hook", "desc": "

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

\n
export async function dynamicInstantiate(url) {\n  return {\n    exports: ['customExportName'],\n    execute: (exports) => {\n      // Get and set functions provided for pre-allocated export names\n      exports.customExportName.set('value');\n    }\n  };\n}\n
\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.

", "type": "misc", "displayName": "Dynamic instantiate hook" } ] }, { "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

isMain is true when resolving the Node.js application entry point.

\n
\nResolver algorithm specification\n

ESM_RESOLVE(specifier, parentURL, isMain)

\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, isMain).
  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

    If packageSpecifier does not start with \"@\", then

    \n
      \n
    1. Set packageName to the substring of packageSpecifier until the\nfirst \"/\" separator or the end of the string.
    2. \n
    \n
  8. \n
  9. \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
  10. \n
  11. \n

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

    \n
      \n
    1. Throw an Invalid Specifier error.
    2. \n
    \n
  12. \n
  13. Let packageSubpath be undefined.
  14. \n
  15. \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
  16. \n
  17. \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
  18. \n
  19. \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
  20. \n
  21. \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
  22. \n
  23. Throw a Module Not Found error.
  24. \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. \n

      If pjson.exports is a String or Array, then

      \n
        \n
      1. Return PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, pjson.exports,\n\"\").
      2. \n
      \n
    2. \n
    3. \n

      If _pjson.exports is an Object, then

      \n
        \n
      1. \n

        If pjson.exports contains a \".\" property, then

        \n
          \n
        1. Let mainExport be the \".\" property in pjson.exports.
        2. \n
        3. Return PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, mainExport,\n\"\").
        4. \n
        \n
      2. \n
      \n
    4. \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. \n

    If exports is an Object, 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\"\").
      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).
        6. \n
        \n
      2. \n
      \n
    8. \n
    \n
  2. \n
  3. Throw a Module Not Found error.
  4. \n
\n
\n

PACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, target, subpath)

\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 an Array, then

    \n
      \n
    1. \n

      For each item targetValue in target, do

      \n
        \n
      1. If targetValue is not a String, continue the loop.
      2. \n
      3. Let resolved be the result of\nPACKAGE_EXPORTS_TARGET_RESOLVE(packageURL, targetValue,\nsubpath), 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
  4. \n
  5. Throw a Module Not Found error.
  6. \n
\n
\n

ESM_FORMAT(url, isMain)

\n
\n
    \n
  1. Assert: url corresponds to an existing file.
  2. \n
  3. Let pjson be the result of READ_PACKAGE_SCOPE(url).
  4. \n
  5. \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 isMain is true or url ends in \".js\", then

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

    Otherwise,

    \n
      \n
    1. \n

      If isMain is true or url ends in \".js\", \".json\" or\n\".node\", 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 --es-module-specifier-resolution=[mode] flag can be used to customize\nthe extension resolution algorithm. The default mode is explicit, which\nrequires the full path to a module be provided to the loader. To enable the\nautomatic extension resolution and importing from directories that include an\nindex file use the node mode.

\n
$ node --experimental-modules index.mjs\nsuccess!\n$ node --experimental-modules index #Failure!\nError: Cannot find module\n$ node --experimental-modules --es-module-specifier-resolution=node index\nsuccess!\n
", "type": "module", "displayName": "Customizing ESM specifier resolution algorithm" } ], "type": "misc", "displayName": "Resolution Algorithm" } ], "properties": [ { "textRaw": "`meta` {Object}", "type": "Object", "name": "meta", "desc": "

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

\n" } ] } ] }