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

The following example of an ES module exports a function:

\n
// addTwo.mjs\nfunction addTwo(num) {\n  return num + 2;\n}\n\nexport { addTwo };\n
\n

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

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

Node.js fully supports ECMAScript modules as they are currently specified and\nprovides 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 will be loaded as ES modules when the nearest parent\npackage.json file contains a top-level field \"type\" with a value of\n\"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\", .js files are treated as CommonJS. If the volume root is\nreached and no package.json is found, Node.js defers to the default, a\npackage.json with no \"type\" field.

\n

import statements of .js files are treated as ES modules if the nearest\nparent 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 folder\nuntil the next folder containing another package.json, are a\npackage scope. The \"type\" field defines how to treat .js files\nwithin the package scope. Every package in a\nproject’s node_modules folder contains its own package.json file, so each\nproject’s dependencies have their own package scopes. If a package.json file\ndoes not have a \"type\" field, the default \"type\" is \"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 -e), or piped to node via\nSTDIN, will be treated as ES modules when the --input-type=module flag is\nset.

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

In a package’s package.json file, two fields can define entry points for a\npackage: \"main\" and \"exports\". The \"main\" field is supported in all\nversions of Node.js, but its capabilities are limited: it only defines the main\nentry point of the package.

\n

The \"exports\" field provides an alternative to \"main\" where the package\nmain entry point can be defined while also encapsulating the package,\npreventing any other entry points besides those defined in \"exports\".\nThis encapsulation allows module authors to define a public interface for\ntheir package.

\n

If both \"exports\" and \"main\" are defined, the \"exports\" field takes\nprecedence over \"main\". \"exports\" are not specific to ES modules or\nCommonJS; \"main\" will be overridden by \"exports\" if it exists. As such\n\"main\" cannot be used as a fallback for CommonJS but it can be used as a\nfallback for legacy versions of Node.js that do not support the \"exports\"\nfield.

\n

Conditional exports can be used within \"exports\" to define different\npackage entry points per environment, including whether the package is\nreferenced via require or via import. For more information about supporting\nboth CommonJS and ES Modules in a single package please consult\nthe dual CommonJS/ES module packages section.

\n

Warning: Introducing the \"exports\" field prevents consumers of a package\nfrom using any entry points that are not defined, including the package.json\n(e.g. require('your-package/package.json'). This will likely be a breaking\nchange.

\n

To make the introduction of \"exports\" non-breaking, ensure that every\npreviously supported entry point is exported. It is best to explicitly specify\nentry points so that the package’s public API is well-defined. For example,\na project that previous exported main, lib,\nfeature, and the package.json could use the following package.exports:

\n
{\n  \"name\": \"my-mod\",\n  \"exports\": {\n    \".\": \"./lib/index.js\",\n    \"./lib\": \"./lib/index.js\",\n    \"./lib/index\": \"./lib/index.js\",\n    \"./lib/index.js\": \"./lib/index.js\",\n    \"./feature\": \"./feature/index.js\",\n    \"./feature/index.js\": \"./feature/index.js\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n
\n

Alternatively a project could choose to export entire folders:

\n
{\n  \"name\": \"my-mod\",\n  \"exports\": {\n    \".\": \"./lib/index.js\",\n    \"./lib\": \"./lib/index.js\",\n    \"./lib/\": \"./lib/\",\n    \"./feature\": \"./feature/index.js\",\n    \"./feature/\": \"./feature/\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n
\n

As a last resort, package encapsulation can be disabled entirely by creating an\nexport for the root of the package \"./\": \"./\". This will expose every file in\nthe package at the cost of disabling the encapsulation and potential tooling\nbenefits this provides. As the ES Module loader in Node.js enforces the use of\nthe full specifier path, exporting the root rather than being explicit\nabout entry is less expressive than either of the prior examples. Not only\nwill encapsulation be lost but module consumers will be unable to\nimport feature from 'my-mod/feature' as they will need to provide the full\npath import feature from 'my-mod/feature/index.js.

", "modules": [ { "textRaw": "Main entry point export", "name": "main_entry_point_export", "desc": "

To set the main entry point for a package, it is advisable to define both\n\"exports\" and \"main\" in the package’s package.json file:

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

The benefit of doing this is that when using the \"exports\" field all\nsubpaths of the package will no longer be available to importers under\nrequire('pkg/subpath.js'), and instead they will get a new error,\nERR_PACKAGE_PATH_NOT_EXPORTED.

\n

This encapsulation of exports provides more reliable guarantees\nabout package interfaces for tools and when handling semver upgrades for a\npackage. It is not a strong encapsulation since a direct require of any\nabsolute subpath of the package such as\nrequire('/path/to/node_modules/pkg/subpath.js') will still load subpath.js.

", "type": "module", "displayName": "Main entry point export" }, { "textRaw": "Subpath exports", "name": "subpath_exports", "desc": "

When using the \"exports\" field, custom subpaths can be defined along\nwith the main entry point by treating the main entry point as the\n\".\" subpath:

\n\n
{\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \".\": \"./main.js\",\n    \"./submodule\": \"./src/submodule.js\"\n  }\n}\n
\n

Now only the defined subpath in \"exports\" can be imported by a\nconsumer:

\n
import submodule from 'es-module-package/submodule';\n// Loads ./node_modules/es-module-package/src/submodule.js\n
\n

While other subpaths will error:

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

Entire 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

With the above, all modules within the ./src/features/ folder\nare exposed deeply to import and require:

\n
import feature from 'es-module-package/features/x.js';\n// Loads ./node_modules/es-module-package/src/features/x.js\n
\n

When using folder mappings, ensure that you do want to expose every\nmodule inside the subfolder. Any modules which are not public\nshould be moved to another folder to retain the encapsulation\nbenefits of exports.

", "type": "module", "displayName": "Subpath exports" }, { "textRaw": "Package exports fallbacks", "name": "package_exports_fallbacks", "desc": "

For possible new specifier support in future, array fallbacks are\nsupported for all invalid specifiers:

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

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

", "type": "module", "displayName": "Package exports fallbacks" }, { "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
", "type": "module", "displayName": "Exports sugar" }, { "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\nrequire() and import can be written:

\n\n
// package.json\n{\n  \"main\": \"./main-require.cjs\",\n  \"exports\": {\n    \"import\": \"./main-module.js\",\n    \"require\": \"./main-require.cjs\"\n  },\n  \"type\": \"module\"\n}\n
\n

Node.js supports the following conditions out of the box:

\n\n

Within the \"exports\" object, key order is significant. During condition\nmatching, earlier entries have higher priority and take precedence over later\nentries. The general rule is that conditions should be from most specific to\nleast specific in object order.

\n

Other conditions such as \"browser\", \"electron\", \"deno\", \"react-native\",\netc. are unknown to, and thus ignored by Node.js. Runtimes or tools other than\nNode.js may use them at their discretion. Further restrictions, definitions, or\nguidance on condition names may occur in the future.

\n

Using the \"import\" and \"require\" conditions can lead to some hazards,\nwhich are further explained in the dual CommonJS/ES module packages section.

\n

Conditional exports can also be extended to exports subpaths, for example:

\n\n
{\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \".\": \"./main.js\",\n    \"./feature\": {\n      \"node\": \"./feature-node.js\",\n      \"default\": \"./feature.js\"\n    }\n  }\n}\n
\n

Defines a package where require('pkg/feature') and import 'pkg/feature'\ncould provide different implementations between Node.js and other JS\nenvironments.

\n

When using environment branches, always include a \"default\" condition where\npossible. Providing a \"default\" condition ensures that any unknown JS\nenvironments are able to use this universal implementation, which helps avoid\nthese JS environments from having to pretend to be existing environments in\norder to support packages with conditional exports. For this reason, using\n\"node\" and \"default\" condition branches is usually preferable to using\n\"node\" and \"browser\" condition branches.

", "type": "module", "displayName": "Conditional exports" }, { "textRaw": "Nested conditions", "name": "nested_conditions", "desc": "

In addition to direct mappings, Node.js also supports nested condition objects.

\n

For example, to define a package that only has dual mode entry points for\nuse in Node.js but not the browser:

\n\n
{\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \"node\": {\n      \"import\": \"./feature-node.mjs\",\n      \"require\": \"./feature-node.cjs\"\n    },\n    \"default\": \"./feature.mjs\",\n  }\n}\n
\n

Conditions continue to be matched in order as with flat conditions. If\na nested conditional does not have any mapping it will continue checking\nthe remaining conditions of the parent condition. In this way nested\nconditions behave analogously to nested JavaScript if statements.

", "type": "module", "displayName": "Nested conditions" }, { "textRaw": "Self-referencing a package using its name", "name": "self-referencing_a_package_using_its_name", "desc": "

Within a package, the values defined in the package’s\npackage.json \"exports\" field can be referenced via the package’s name.\nFor example, assuming the package.json is:

\n
// package.json\n{\n  \"name\": \"a-package\",\n  \"exports\": {\n    \".\": \"./main.mjs\",\n    \"./foo\": \"./foo.js\"\n  }\n}\n
\n

Then any module in that package can reference an export in the package itself:

\n
// ./a-module.mjs\nimport { something } from 'a-package'; // Imports \"something\" from ./main.mjs.\n
\n

Self-referencing is available only if package.json has exports, and will\nallow importing only what that exports (in the package.json) allows.\nSo the code below, given the package above, will generate a runtime error:

\n
// ./another-module.mjs\n\n// Imports \"another\" from ./m.mjs. Fails because\n// the \"package.json\" \"exports\" field\n// does not provide an export named \"./m.mjs\".\nimport { another } from 'a-package/m.mjs';\n
\n

Self-referencing is also available when using require, both in an ES module,\nand in a CommonJS one. For example, this code will also work:

\n
// ./a-module.js\nconst { something } = require('a-package/foo'); // Loads from ./foo.js.\n
", "type": "module", "displayName": "Self-referencing a package using its name" } ], "type": "module", "displayName": "Package entry points" }, { "textRaw": "Internal package imports", "name": "internal_package_imports", "desc": "

In addition to the \"exports\" field it is possible to define internal package\nimport maps that only apply to import specifiers from within the package itself.

\n

Entries in the imports field must always start with # to ensure they are\nclearly disambiguated from package specifiers.

\n

For example, the imports field can be used to gain the benefits of conditional\nexports for internal modules:

\n
// package.json\n{\n  \"imports\": {\n    \"#dep\": {\n      \"node\": \"dep-node-native\",\n      \"default\": \"./dep-polyfill.js\"\n    }\n  },\n  \"dependencies\": {\n    \"dep-node-native\": \"^1.0.0\"\n  }\n}\n
\n

where import '#dep' would now get the resolution of the external package\ndep-node-native (including its exports in turn), and instead get the local\nfile ./dep-polyfill.js relative to the package in other environments.

\n

Unlike the exports field, import maps permit mapping to external packages\nbecause this provides an important use case for conditional loading and also can\nbe done without the risk of cycles, unlike for exports.

\n

Apart from the above, the resolution rules for the imports field are otherwise\nanalogous to the exports field.

", "type": "module", "displayName": "Internal package imports" }, { "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 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    \"import\": \"./wrapper.mjs\",\n    \"require\": \"./index.cjs\"\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": "

A package.json file can define the separate CommonJS and ES module entry\npoints 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.resolve`", "name": "no_`require.resolve`", "desc": "

Former use cases relying on require.resolve to determine the resolved path\nof a module can be supported via import.meta.resolve, which is experimental\nand supported via the --experimental-import-meta-resolve flag:

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

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

\n
(async () => {\n  // Equivalent to import.meta.resolve('./dep')\n  await import.meta.resolve('./dep', import.meta.url);\n})();\n
\n

This function is asynchronous since the ES module resolver in Node.js is\nasynchronous. With the introduction of Top-Level Await, these use cases\nwill be easier as they won't require an async function wrapper.

", "type": "module", "displayName": "No `require.resolve`" }, { "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
\n

It is also possible to\nimport an ES or CommonJS module for its side effects only.

", "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\nused to include ES module files from CommonJS code.

", "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 top-level `await`", "name": "experimental_top-level_`await`", "desc": "

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

\n

Assuming an a.mjs with

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

And a b.mjs with

\n
import { five } from './a.mjs';\n\nconsole.log(five); // Logs `5`\n
\n
node b.mjs # works\n
", "type": "misc", "displayName": "Experimental top-level `await`" }, { "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", "methods": [ { "textRaw": "`resolve(specifier, context, defaultResolve)`", "type": "method", "name": "resolve", "signatures": [ { "params": [] } ], "desc": "
\n

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

\n
\n\n

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

\n

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

\n

The current package exports conditions will always be in\nthe context.conditions array passed into the hook. To guarantee default\nNode.js module specifier resolution behavior when calling defaultResolve, the\ncontext.conditions array passed to it must include all elements of the\ncontext.conditions array originally passed into the resolve hook.

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

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

\n
\n\n

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

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

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

\n\n

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

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

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

\n
\n\n

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

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

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

\n
\n\n

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

\n

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

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

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

\n
\n\n

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

\n

Similar to how CommonJS wrappers work, the code runs in an implicit function\nscope. The only argument is a require-like function that can be used to load\nbuiltins like \"fs\": getBuiltin(request: string).

\n

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

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

Examples

\n

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

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

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

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

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

\n

The algorithm to determine the module format of a resolved URL is\nprovided by ESM_FORMAT, which returns the unique module\nformat for any file. The \"module\" format is returned for an ECMAScript\nModule, while the \"commonjs\" format is used to indicate loading through the\nlegacy CommonJS loader. Additional formats such as \"addon\" can be extended in\nfuture updates.

\n

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

\n

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

\n

The resolver can throw the following errors:

\n\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 \"/\", \"./\" or \"../\", then

    \n
      \n
    1. Set resolvedURL to the URL resolution of specifier relative to\nparentURL.
    2. \n
    \n
  6. \n
  7. \n

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

    \n
      \n
    1. Set resolvedURL to the result of\nPACKAGE_INTERNAL_RESOLVE(specifier, parentURL).
    2. \n
    3. If resolvedURL is null or undefined, throw a\nPackage Import Not Defined error.
    4. \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 Module Specifier error.
    2. \n
    \n
  12. \n
  13. \n

    If the file at resolvedURL is a directory, then

    \n
      \n
    1. Throw an Unsupported Directory Import error.
    2. \n
    \n
  14. \n
  15. \n

    If the file at resolvedURL does not exist, then

    \n
      \n
    1. Throw a Module Not Found error.
    2. \n
    \n
  16. \n
  17. Set resolvedURL to the real path of resolvedURL.
  18. \n
  19. Let format be the result of ESM_FORMAT(resolvedURL).
  20. \n
  21. Load resolvedURL as module format, format.
  22. \n
  23. Return resolvedURL.
  24. \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 Module 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 Module Specifier error.
      2. \n
      \n
    2. \n
    3. Set packageName to the substring of packageSpecifier\nuntil the second \"/\" separator or the end of the string.
    4. \n
    \n
  8. \n
  9. \n

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

    \n
      \n
    1. Throw an Invalid Module Specifier error.
    2. \n
    \n
  10. \n
  11. Let packageSubpath be 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 Module Specifier error.
    2. \n
    \n
  16. \n
  17. Let selfUrl be 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 \"nodejs:\" 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 equal to \"./\", then

      \n
        \n
      1. Return packageURL + \"/\".
      2. \n
      \n
    10. \n
    11. \n

      If packageSubpath is _undefined__, then

      \n
        \n
      1. Return the result of PACKAGE_MAIN_RESOLVE(packageURL,\npjson).
      2. \n
      \n
    12. \n
    13. \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. Let resolved be the result of PACKAGE_EXPORTS_RESOLVE(\npackageURL, packageSubpath, pjson.exports).
          2. \n
          3. If resolved is null or undefined, throw a\nPackage Path Not Exported error.
          4. \n
          5. Return resolved.
          6. \n
          \n
        4. \n
        \n
      2. \n
      3. Return the URL resolution of packageSubpath in packageURL.
      4. \n
      \n
    14. \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 equal to \"./\", then

      \n
        \n
      1. Return packageURL + \"/\".
      2. \n
      \n
    2. \n
    3. \n

      If packageSubpath is undefined, then

      \n
        \n
      1. Return the result of PACKAGE_MAIN_RESOLVE(packageURL, pjson).
      2. \n
      \n
    4. \n
    5. \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. Let resolved be the result of PACKAGE_EXPORTS_RESOLVE(\npackageURL, subpath, pjson.exports).
          2. \n
          3. If resolved is null or undefined, throw a\nPackage Path Not Exported error.
          4. \n
          5. Return resolved.
          6. \n
          \n
        4. \n
        \n
      2. \n
      3. Return the URL resolution of subpath in packageURL.
      4. \n
      \n
    6. \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. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, pjson.exports, \"\", false, defaultEnv).
      2. \n
      3. If resolved is null or undefined, throw a\nPackage Path Not Exported error.
      4. \n
      5. Return resolved.
      6. \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. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, \"\", false, defaultEnv).
      4. \n
      5. If resolved is null or undefined, throw a\nPackage Path Not Exported error.
      6. \n
      7. Return resolved.
      8. \n
      \n
    6. \n
    7. Throw a Package Path Not Exported error.
    8. \n
    \n
  4. \n
  5. Let legacyMainURL be the result applying the legacy\nLOAD_AS_DIRECTORY CommonJS resolver to packageURL, throwing a\nModule Not Found error for no resolution.
  6. \n
  7. Return legacyMainURL.
  8. \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_TARGET_RESOLVE(packageURL, target,\n\"\", false, 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_TARGET_RESOLVE(packageURL, target,\nsubpath, false, defaultEnv).
        6. \n
        \n
      2. \n
      \n
    8. \n
    \n
  4. \n
  5. Return null.
  6. \n
\n
\n

PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, internal, env)

\n
\n
    \n
  1. \n

    If target is a String, then

    \n
      \n
    1. If target contains any \"node_modules\" segments including\n\"node_modules\" percent-encoding, throw an Invalid Package Target\nerror.
    2. \n
    3. If subpath has non-zero length and target does not end with \"/\",\nthrow an Invalid Module Specifier error.
    4. \n
    5. \n

      If target does not start with \"./\", then

      \n
        \n
      1. \n

        If target does not start with \"../\" or \"/\" and is not a valid\nURL, then

        \n
          \n
        1. If internal is true, return PACKAGE_RESOLVE(\ntarget + subpath, packageURL + \"/\")_.
        2. \n
        \n
      2. \n
      3. Otherwise throw an Invalid Package Target error.
      4. \n
      \n
    6. \n
    7. Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
    8. \n
    9. If resolvedTarget is not contained in packageURL, throw an\nInvalid Package Target error.
    10. \n
    11. Let resolved be the URL resolution of the concatenation of\nsubpath and resolvedTarget.
    12. \n
    13. If resolved is not contained in resolvedTarget, throw an\nInvalid Module Specifier error.
    14. \n
    15. Return resolved.
    16. \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 p equals \"default\" or 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_TARGET_RESOLVE(\npackageURL, targetValue, subpath, internal, env)
        4. \n
        5. If resolved is equal to undefined, continue the loop.
        6. \n
        7. Return resolved.
        8. \n
        \n
      2. \n
      \n
    4. \n
    5. Return undefined.
    6. \n
    \n
  4. \n
  5. \n

    Otherwise, if target is an Array, then

    \n
      \n
    1. If _target.length is zero, return null.
    2. \n
    3. \n

      For each item targetValue in target, do

      \n
        \n
      1. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, internal, env),\ncontinuing the loop on any Invalid Package Target error.
      2. \n
      3. If resolved is undefined, continue the loop.
      4. \n
      5. Return resolved.
      6. \n
      \n
    4. \n
    5. Return or throw the last fallback resolution null return or error.
    6. \n
    \n
  6. \n
  7. Otherwise, if target is null, return null.
  8. \n
  9. Otherwise throw an Invalid Package Target error.
  10. \n
\n
\n

PACKAGE_INTERNAL_RESOLVE(specifier, parentURL)

\n
\n
    \n
  1. Assert: specifier begins with \"#\".
  2. \n
  3. \n

    If specifier is exactly equal to \"#\" or starts with \"#/\", then

    \n
      \n
    1. Throw an Invalid Module Specifier error.
    2. \n
    \n
  4. \n
  5. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
  6. \n
  7. \n

    If packageURL is not null, then

    \n
      \n
    1. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
    2. \n
    3. \n

      If _pjson.imports is a non-null Object, then

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

        If specifier is a key of imports, then

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

        For each key directory in directoryKeys, do

        \n
          \n
        1. \n

          If specifier starts with directory, then

          \n
            \n
          1. Let target be the value of imports[directory].
          2. \n
          3. Let subpath be the substring of target starting at the\nindex of the length of directory.
          4. \n
          5. Return PACKAGE_TARGET_RESOLVE(packageURL, target,\nsubpath, true, defaultEnv).
          6. \n
          \n
        2. \n
        \n
      8. \n
      \n
    4. \n
    \n
  8. \n
  9. Return null.
  10. \n
\n
\n

ESM_FORMAT(url)

\n
\n
    \n
  1. Assert: url corresponds to an existing file.
  2. \n
  3. Let pjson be the result of READ_PACKAGE_SCOPE(url).
  4. \n
  5. \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\", 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. Throw an Unsupported File Extension error.
    2. \n
    \n
  12. \n
\n
\n

READ_PACKAGE_SCOPE(url)

\n
\n
    \n
  1. Let scopeURL be url.
  2. \n
  3. \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" } ] } ] }