lts/doc/api/esm.json
{
"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": "<p>The <code>import.meta</code> metaproperty is an <code>Object</code> that contains the following\nproperty:</p>\n<ul>\n<li><code>url</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\"><string></a> The absolute <code>file:</code> URL of the module.</li>\n</ul>"
}
],
"miscs": [
{
"textRaw": "ECMAScript modules",
"name": "ECMAScript modules",
"introduced_in": "v8.5.0",
"type": "misc",
"stability": 1,
"stabilityText": "Experimental",
"miscs": [
{
"textRaw": "Introduction",
"name": "esm",
"desc": "<p>ECMAScript modules are <a href=\"https://tc39.github.io/ecma262/#sec-modules\">the official standard format</a> to package JavaScript\ncode for reuse. Modules are defined using a variety of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import\"><code>import</code></a> and\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export\"><code>export</code></a> statements.</p>\n<p>The following example of an ES module exports a function:</p>\n<pre><code class=\"language-js\">// addTwo.mjs\nfunction addTwo(num) {\n return num + 2;\n}\n\nexport { addTwo };\n</code></pre>\n<p>The following example of an ES module imports the function from <code>addTwo.mjs</code>:</p>\n<pre><code class=\"language-js\">// app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));\n</code></pre>\n<p>Node.js fully supports ECMAScript modules as they are currently specified and\nprovides limited interoperability between them and the existing module format,\n<a href=\"modules.html\">CommonJS</a>.</p>\n<p>Node.js contains support for ES Modules based upon the\n<a href=\"https://github.com/nodejs/node-eps/blob/master/002-es-modules.md\">Node.js EP for ES Modules</a> and the <a href=\"https://github.com/nodejs/modules/blob/master/doc/plan-for-new-modules-implementation.md\">ECMAScript-modules implementation</a>.</p>\n<p>Expect major changes in the implementation including interoperability support,\nspecifier resolution, and default behavior.</p>",
"type": "misc",
"displayName": "esm"
},
{
"textRaw": "Enabling",
"name": "Enabling",
"type": "misc",
"desc": "<p>Experimental support for ECMAScript modules is enabled by default.\nNode.js will treat the following as ES modules when passed to <code>node</code> as the\ninitial input, or when referenced by <code>import</code> statements within ES module code:</p>\n<ul>\n<li>\n<p>Files ending in <code>.mjs</code>.</p>\n</li>\n<li>\n<p>Files ending in <code>.js</code> when the nearest parent <code>package.json</code> file contains a\ntop-level field <code>\"type\"</code> with a value of <code>\"module\"</code>.</p>\n</li>\n<li>\n<p>Strings passed in as an argument to <code>--eval</code> or <code>--print</code>, or piped to\n<code>node</code> via <code>STDIN</code>, with the flag <code>--input-type=module</code>.</p>\n</li>\n</ul>\n<p>Node.js will treat as CommonJS all other forms of input, such as <code>.js</code> files\nwhere the nearest parent <code>package.json</code> file contains no top-level <code>\"type\"</code>\nfield, or string input without the flag <code>--input-type</code>. 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 <code>node</code> as the initial input,\nor when referenced by <code>import</code> statements within ES module code:</p>\n<ul>\n<li>\n<p>Files ending in <code>.cjs</code>.</p>\n</li>\n<li>\n<p>Files ending in <code>.js</code> when the nearest parent <code>package.json</code> file contains a\ntop-level field <code>\"type\"</code> with a value of <code>\"commonjs\"</code>.</p>\n</li>\n<li>\n<p>Strings passed in as an argument to <code>--eval</code> or <code>--print</code>, or piped to\n<code>node</code> via <code>STDIN</code>, with the flag <code>--input-type=commonjs</code>.</p>\n</li>\n</ul>",
"miscs": [
{
"textRaw": "`package.json` `\"type\"` field",
"name": "`package.json`_`\"type\"`_field",
"desc": "<p>Files ending with <code>.js</code> will be loaded as ES modules when the nearest parent\n<code>package.json</code> file contains a top-level field <code>\"type\"</code> with a value of\n<code>\"module\"</code>.</p>\n<p>The nearest parent <code>package.json</code> is defined as the first <code>package.json</code> found\nwhen searching in the current folder, that folder’s parent, and so on up\nuntil the root of the volume is reached.</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">// package.json\n{\n \"type\": \"module\"\n}\n</code></pre>\n<pre><code class=\"language-bash\"># In same folder as above package.json\nnode my-app.js # Runs as ES module\n</code></pre>\n<p>If the nearest parent <code>package.json</code> lacks a <code>\"type\"</code> field, or contains\n<code>\"type\": \"commonjs\"</code>, <code>.js</code> files are treated as CommonJS. If the volume root is\nreached and no <code>package.json</code> is found, Node.js defers to the default, a\n<code>package.json</code> with no <code>\"type\"</code> field.</p>\n<p><code>import</code> statements of <code>.js</code> files are treated as ES modules if the nearest\nparent <code>package.json</code> contains <code>\"type\": \"module\"</code>.</p>\n<pre><code class=\"language-js\">// my-app.js, part of the same example as above\nimport './startup.js'; // Loaded as ES module because of package.json\n</code></pre>\n<p>Package authors should include the <code>\"type\"</code> field, even in packages where all\nsources are CommonJS. Being explicit about the <code>type</code> 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.</p>\n<p>Regardless of the value of the <code>\"type\"</code> field, <code>.mjs</code> files are always treated\nas ES modules and <code>.cjs</code> files are always treated as CommonJS.</p>",
"type": "misc",
"displayName": "`package.json` `\"type\"` field"
},
{
"textRaw": "Package scope and file extensions",
"name": "package_scope_and_file_extensions",
"desc": "<p>A folder containing a <code>package.json</code> file, and all subfolders below that folder\ndown until the next folder containing another <code>package.json</code>, is considered a\n<em>package scope</em>. The <code>\"type\"</code> field defines how <code>.js</code> files should be treated\nwithin a particular <code>package.json</code> file’s package scope. Every package in a\nproject’s <code>node_modules</code> folder contains its own <code>package.json</code> file, so each\nproject’s dependencies have their own package scopes. A <code>package.json</code> lacking a\n<code>\"type\"</code> field is treated as if it contained <code>\"type\": \"commonjs\"</code>.</p>\n<p>The package scope applies not only to initial entry points (<code>node my-app.js</code>)\nbut also to files referenced by <code>import</code> statements and <code>import()</code> expressions.</p>\n<pre><code class=\"language-js\">// 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</code></pre>\n<p>Files ending with <code>.mjs</code> are always loaded as ES modules regardless of package\nscope.</p>\n<p>Files ending with <code>.cjs</code> are always loaded as CommonJS regardless of package\nscope.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>The <code>.mjs</code> and <code>.cjs</code> extensions may be used to mix types within the same\npackage scope:</p>\n<ul>\n<li>\n<p>Within a <code>\"type\": \"module\"</code> package scope, Node.js can be instructed to\ninterpret a particular file as CommonJS by naming it with a <code>.cjs</code> extension\n(since both <code>.js</code> and <code>.mjs</code> files are treated as ES modules within a\n<code>\"module\"</code> package scope).</p>\n</li>\n<li>\n<p>Within a <code>\"type\": \"commonjs\"</code> package scope, Node.js can be instructed to\ninterpret a particular file as an ES module by naming it with an <code>.mjs</code>\nextension (since both <code>.js</code> and <code>.cjs</code> files are treated as CommonJS within a\n<code>\"commonjs\"</code> package scope).</p>\n</li>\n</ul>",
"type": "misc",
"displayName": "Package scope and file extensions"
},
{
"textRaw": "`--input-type` flag",
"name": "`--input-type`_flag",
"desc": "<p>Strings passed in as an argument to <code>--eval</code> or <code>--print</code> (or <code>-e</code> or <code>-p</code>), or\npiped to <code>node</code> via <code>STDIN</code>, will be treated as ES modules when the\n<code>--input-type=module</code> flag is set.</p>\n<pre><code class=\"language-bash\">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</code></pre>\n<p>For completeness there is also <code>--input-type=commonjs</code>, for explicitly running\nstring input as CommonJS. This is the default behavior if <code>--input-type</code> is\nunspecified.</p>",
"type": "misc",
"displayName": "`--input-type` flag"
}
]
},
{
"textRaw": "Packages",
"name": "packages",
"modules": [
{
"textRaw": "Package entry points",
"name": "package_entry_points",
"desc": "<p>In a package’s <code>package.json</code> file, two fields can define entry points for a\npackage: <code>\"main\"</code> and <code>\"exports\"</code>. The <code>\"main\"</code> field is supported in all\nversions of Node.js, but its capabilities are limited: it only defines the main\nentry point of the package.</p>\n<p>The <code>\"exports\"</code> field provides an alternative to <code>\"main\"</code> where the package\nmain entry point can be defined while also encapsulating the package,\n<strong>preventing any other entry points besides those defined in <code>\"exports\"</code></strong>.\nThis encapsulation allows module authors to define a public interface for\ntheir package.</p>\n<p>If both <code>\"exports\"</code> and <code>\"main\"</code> are defined, the <code>\"exports\"</code> field takes\nprecedence over <code>\"main\"</code>. <code>\"exports\"</code> are not specific to ES modules or\nCommonJS; <code>\"main\"</code> will be overridden by <code>\"exports\"</code> if it exists. As such\n<code>\"main\"</code> 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 <code>\"exports\"</code>\nfield.</p>\n<p><a href=\"#esm_conditional_exports\">Conditional exports</a> can be used within <code>\"exports\"</code> to define different\npackage entry points per environment, including whether the package is\nreferenced via <code>require</code> or via <code>import</code>. For more information about supporting\nboth CommonJS and ES Modules in a single package please consult\n<a href=\"#esm_dual_commonjs_es_module_packages\">the dual CommonJS/ES module packages section</a>.</p>\n<p><strong>Warning</strong>: Introducing the <code>\"exports\"</code> field prevents consumers of a package\nfrom using any entry points that are not defined, including the <code>package.json</code>\n(e.g. <code>require('your-package/package.json')</code>. <strong>This will likely be a breaking\nchange.</strong></p>\n<p>To make the introduction of <code>\"exports\"</code> 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 <code>main</code>, <code>lib</code>,\n<code>feature</code>, and the <code>package.json</code> could use the following <code>package.exports</code>:</p>\n<pre><code class=\"language-json\">{\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</code></pre>\n<p>Alternatively a project could choose to export entire folders:</p>\n<pre><code class=\"language-json\">{\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</code></pre>\n<p>As a last resort, package encapsulation can be disabled entirely by creating an\nexport for the root of the package <code>\"./\": \"./\"</code>. 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\n<a href=\"#esm_mandatory_file_extensions\">the full specifier path</a>, 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\n<code>import feature from 'my-mod/feature'</code> as they will need to provide the full\npath <code>import feature from 'my-mod/feature/index.js</code>.</p>",
"modules": [
{
"textRaw": "Main entry point export",
"name": "main_entry_point_export",
"desc": "<p>To set the main entry point for a package, it is advisable to define both\n<code>\"exports\"</code> and <code>\"main\"</code> in the package’s <code>package.json</code> file:</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">{\n \"main\": \"./main.js\",\n \"exports\": \"./main.js\"\n}\n</code></pre>\n<p>The benefit of doing this is that when using the <code>\"exports\"</code> field all\nsubpaths of the package will no longer be available to importers under\n<code>require('pkg/subpath.js')</code>, and instead they will get a new error,\n<code>ERR_PACKAGE_PATH_NOT_EXPORTED</code>.</p>\n<p>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\n<code>require('/path/to/node_modules/pkg/subpath.js')</code> will still load <code>subpath.js</code>.</p>",
"type": "module",
"displayName": "Main entry point export"
},
{
"textRaw": "Subpath exports",
"name": "subpath_exports",
"desc": "<p>When using the <code>\"exports\"</code> field, custom subpaths can be defined along\nwith the main entry point by treating the main entry point as the\n<code>\".\"</code> subpath:</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">{\n \"main\": \"./main.js\",\n \"exports\": {\n \".\": \"./main.js\",\n \"./submodule\": \"./src/submodule.js\"\n }\n}\n</code></pre>\n<p>Now only the defined subpath in <code>\"exports\"</code> can be imported by a\nconsumer:</p>\n<pre><code class=\"language-js\">import submodule from 'es-module-package/submodule';\n// Loads ./node_modules/es-module-package/src/submodule.js\n</code></pre>\n<p>While other subpaths will error:</p>\n<pre><code class=\"language-js\">import submodule from 'es-module-package/private-module.js';\n// Throws ERR_PACKAGE_PATH_NOT_EXPORTED\n</code></pre>\n<p>Entire folders can also be mapped with package exports:</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">// ./node_modules/es-module-package/package.json\n{\n \"exports\": {\n \"./features/\": \"./src/features/\"\n }\n}\n</code></pre>\n<p>With the above, all modules within the <code>./src/features/</code> folder\nare exposed deeply to <code>import</code> and <code>require</code>:</p>\n<pre><code class=\"language-js\">import feature from 'es-module-package/features/x.js';\n// Loads ./node_modules/es-module-package/src/features/x.js\n</code></pre>\n<p>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.</p>",
"type": "module",
"displayName": "Subpath exports"
},
{
"textRaw": "Package exports fallbacks",
"name": "package_exports_fallbacks",
"desc": "<p>For possible new specifier support in future, array fallbacks are\nsupported for all invalid specifiers:</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">{\n \"exports\": {\n \"./submodule\": [\"not:valid\", \"./submodule.js\"]\n }\n}\n</code></pre>\n<p>Since <code>\"not:valid\"</code> is not a valid specifier, <code>\"./submodule.js\"</code> is used\ninstead as the fallback, as if it were the only target.</p>",
"type": "module",
"displayName": "Package exports fallbacks"
},
{
"textRaw": "Exports sugar",
"name": "exports_sugar",
"desc": "<p>If the <code>\".\"</code> export is the only export, the <code>\"exports\"</code> field provides sugar\nfor this case being the direct <code>\"exports\"</code> field value.</p>\n<p>If the <code>\".\"</code> export has a fallback array or string value, then the <code>\"exports\"</code>\nfield can be set to this value directly.</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">{\n \"exports\": {\n \".\": \"./main.js\"\n }\n}\n</code></pre>\n<p>can be written:</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">{\n \"exports\": \"./main.js\"\n}\n</code></pre>",
"type": "module",
"displayName": "Exports sugar"
},
{
"textRaw": "Conditional exports",
"name": "conditional_exports",
"desc": "<p>Conditional exports provide a way to map to different paths depending on\ncertain conditions. They are supported for both CommonJS and ES module imports.</p>\n<p>For example, a package that wants to provide different ES module exports for\n<code>require()</code> and <code>import</code> can be written:</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">// 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</code></pre>\n<p>Node.js supports the following conditions:</p>\n<ul>\n<li><code>\"import\"</code> - matched when the package is loaded via <code>import</code> or\n<code>import()</code>. Can reference either an ES module or CommonJS file, as both\n<code>import</code> and <code>import()</code> can load either ES module or CommonJS sources.</li>\n<li><code>\"require\"</code> - matched when the package is loaded via <code>require()</code>.\nAs <code>require()</code> only supports CommonJS, the referenced file must be CommonJS.</li>\n<li><code>\"node\"</code> - matched for any Node.js environment. Can be a CommonJS or ES\nmodule file. <em>This condition should always come after <code>\"import\"</code> or\n<code>\"require\"</code>.</em></li>\n<li><code>\"default\"</code> - the generic fallback that will always match. Can be a CommonJS\nor ES module file. <em>This condition should always come last.</em></li>\n</ul>\n<p>Condition matching is applied in object order from first to last within the\n<code>\"exports\"</code> object. <em>The general rule is that conditions should be used\nfrom most specific to least specific in object order.</em></p>\n<p>Other conditions such as <code>\"browser\"</code>, <code>\"electron\"</code>, <code>\"deno\"</code>, <code>\"react-native\"</code>,\netc. are ignored by Node.js but may be used by other runtimes or tools.\nFurther restrictions, definitions or guidance on condition names may be\nprovided in the future.</p>\n<p>Using the <code>\"import\"</code> and <code>\"require\"</code> conditions can lead to some hazards,\nwhich are explained further in\n<a href=\"#esm_dual_commonjs_es_module_packages\">the dual CommonJS/ES module packages section</a>.</p>\n<p>Conditional exports can also be extended to exports subpaths, for example:</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">{\n \"main\": \"./main.js\",\n \"exports\": {\n \".\": \"./main.js\",\n \"./feature\": {\n \"browser\": \"./feature-browser.js\",\n \"default\": \"./feature.js\"\n }\n }\n}\n</code></pre>\n<p>Defines a package where <code>require('pkg/feature')</code> and <code>import 'pkg/feature'</code>\ncould provide different implementations between the browser and Node.js,\ngiven third-party tool support for a <code>\"browser\"</code> condition.</p>",
"type": "module",
"displayName": "Conditional exports"
},
{
"textRaw": "Nested conditions",
"name": "nested_conditions",
"desc": "<p>In addition to direct mappings, Node.js also supports nested condition objects.</p>\n<p>For example, to define a package that only has dual mode entry points for\nuse in Node.js but not the browser:</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">{\n \"main\": \"./main.js\",\n \"exports\": {\n \"browser\": \"./feature-browser.mjs\",\n \"node\": {\n \"import\": \"./feature-node.mjs\",\n \"require\": \"./feature-node.cjs\"\n }\n }\n}\n</code></pre>\n<p>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 <code>if</code> statements.</p>",
"type": "module",
"displayName": "Nested conditions"
},
{
"textRaw": "Self-referencing a package using its name",
"name": "self-referencing_a_package_using_its_name",
"desc": "<p>Within a package, the values defined in the package’s\n<code>package.json</code> <code>\"exports\"</code> field can be referenced via the package’s name.\nFor example, assuming the <code>package.json</code> is:</p>\n<pre><code class=\"language-json\">// package.json\n{\n \"name\": \"a-package\",\n \"exports\": {\n \".\": \"./main.mjs\",\n \"./foo\": \"./foo.js\"\n }\n}\n</code></pre>\n<p>Then any module <em>in that package</em> can reference an export in the package itself:</p>\n<pre><code class=\"language-js\">// ./a-module.mjs\nimport { something } from 'a-package'; // Imports \"something\" from ./main.mjs.\n</code></pre>\n<p>Self-referencing is available only if <code>package.json</code> has <code>exports</code>, and will\nallow importing only what that <code>exports</code> (in the <code>package.json</code>) allows.\nSo the code below, given the package above, will generate a runtime error:</p>\n<pre><code class=\"language-js\">// ./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</code></pre>\n<p>Self-referencing is also available when using <code>require</code>, both in an ES module,\nand in a CommonJS one. For example, this code will also work:</p>\n<pre><code class=\"language-js\">// ./a-module.js\nconst { something } = require('a-package/foo'); // Loads from ./foo.js.\n</code></pre>",
"type": "module",
"displayName": "Self-referencing a package using its name"
}
],
"type": "module",
"displayName": "Package entry points"
},
{
"textRaw": "Dual CommonJS/ES module packages",
"name": "dual_commonjs/es_module_packages",
"desc": "<p>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 <code>package.json</code> <code>\"main\"</code> specifying the CommonJS\nentry point and <code>package.json</code> <code>\"module\"</code> 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 <code>\"module\"</code> field.</p>\n<p>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<code>'pkg'</code> and <code>'pkg/es-module'</code>, or both at the same specifier via <a href=\"#esm_conditional_exports\">Conditional\nexports</a>). Unlike in the scenario where <code>\"module\"</code> 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.</p>",
"modules": [
{
"textRaw": "Dual package hazard",
"name": "dual_package_hazard",
"desc": "<p>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 <code>pkgInstance</code> created by\n<code>const pkgInstance = require('pkg')</code> is not the same as the <code>pkgInstance</code>\ncreated by <code>import pkgInstance from 'pkg'</code> (or an alternative main path like\n<code>'pkg/module'</code>). 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.</p>\n<p>If the package main export is a constructor, an <code>instanceof</code> comparison of\ninstances created by the two versions returns <code>false</code>, and if the export is an\nobject, properties added to one (like <code>pkgInstance.foo = 3</code>) are not present on\nthe other. This differs from how <code>import</code> and <code>require</code> 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 <a href=\"https://babeljs.io/\">Babel</a> or <a href=\"https://github.com/standard-things/esm#readme\"><code>esm</code></a>.</p>",
"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": "<p>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 <code>import</code> can refer to CommonJS\nfiles; but it would not provide any of the advantages of using ES module syntax.</p>\n<p>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.</p>\n<p>Every pattern has tradeoffs, but there are two broad approaches that satisfy the\nfollowing conditions:</p>\n<ol>\n<li>The package is usable via both <code>require</code> and <code>import</code>.</li>\n<li>The package is usable in both current Node.js and older versions of Node.js\nthat lack support for ES modules.</li>\n<li>The package main entry point, e.g. <code>'pkg'</code> can be used by both <code>require</code> to\nresolve to a CommonJS file and by <code>import</code> to resolve to an ES module file.\n(And likewise for exported paths, e.g. <code>'pkg/feature'</code>.)</li>\n<li>The package provides named exports, e.g. <code>import { name } from 'pkg'</code> rather\nthan <code>import pkg from 'pkg'; pkg.name</code>.</li>\n<li>The package is potentially usable in other ES module environments such as\nbrowsers.</li>\n<li>The hazards described in the previous section are avoided or minimized.</li>\n</ol>",
"modules": [
{
"textRaw": "Approach #1: Use an ES module wrapper",
"name": "approach_#1:_use_an_es_module_wrapper",
"desc": "<p>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\n<a href=\"#esm_conditional_exports\">Conditional exports</a>, the ES module wrapper is used for <code>import</code> and the\nCommonJS entry point for <code>require</code>.</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">// ./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</code></pre>\n<pre><code class=\"language-js\">// ./node_modules/pkg/index.cjs\nexports.name = 'value';\n</code></pre>\n<pre><code class=\"language-js\">// ./node_modules/pkg/wrapper.mjs\nimport cjsModule from './index.cjs';\nexport const name = cjsModule.name;\n</code></pre>\n<p>In this example, the <code>name</code> from <code>import { name } from 'pkg'</code> is the same\nsingleton as the <code>name</code> from <code>const { name } = require('pkg')</code>. Therefore <code>===</code>\nreturns <code>true</code> when comparing the two <code>name</code>s and the divergent specifier hazard\nis avoided.</p>\n<p>If the module is not simply a list of named exports, but rather contains a\nunique function or object export like <code>module.exports = function () { ... }</code>,\nor if support in the wrapper for the <code>import pkg from 'pkg'</code> pattern is desired,\nthen the wrapper would instead be written to export the default optionally\nalong with any named exports as well:</p>\n<pre><code class=\"language-js\">import cjsModule from './index.cjs';\nexport const name = cjsModule.name;\nexport default cjsModule;\n</code></pre>\n<p>This approach is appropriate for any of the following use cases:</p>\n<ul>\n<li>The package is currently written in CommonJS and the author would prefer not\nto refactor it into ES module syntax, but wishes to provide named exports for\nES module consumers.</li>\n<li>The package has other packages that depend on it, and the end user might\ninstall both this package and those other packages. For example a <code>utilities</code>\npackage is used directly in an application, and a <code>utilities-plus</code> package\nadds a few more functions to <code>utilities</code>. Because the wrapper exports\nunderlying CommonJS files, it doesn’t matter if <code>utilities-plus</code> is written in\nCommonJS or ES module syntax; it will work either way.</li>\n<li>The package stores internal state, and the package author would prefer not to\nrefactor the package to isolate its state management. See the next section.</li>\n</ul>\n<p>A variant of this approach not requiring conditional exports for consumers could\nbe to add an export, e.g. <code>\"./module\"</code>, to point to an all-ES module-syntax\nversion of the package. This could be used via <code>import 'pkg/module'</code> 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):</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">// ./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</code></pre>",
"type": "module",
"displayName": "Approach #1: Use an ES module wrapper"
},
{
"textRaw": "Approach #2: Isolate state",
"name": "approach_#2:_isolate_state",
"desc": "<p>A <code>package.json</code> file can define the separate CommonJS and ES module entry\npoints directly:</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">// ./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</code></pre>\n<p>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).</p>\n<p>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 <code>import</code> the ES module version while a dependency\n<code>require</code>s 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.</p>\n<p>Aside from writing a stateless package (if JavaScript’s <code>Math</code> 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:</p>\n<ol>\n<li>\n<p>If possible, contain all state within an instantiated object. JavaScript’s\n<code>Date</code>, for example, needs to be instantiated to contain state; if it were a\npackage, it would be used like this:</p>\n<pre><code class=\"language-js\">import Date from 'date';\nconst someDate = new Date();\n// someDate contains state; Date does not\n</code></pre>\n<p>The <code>new</code> 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.</p>\n</li>\n<li>\n<p>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 <code>index.cjs</code> and <code>index.mjs</code>, respectively:</p>\n<pre><code class=\"language-js\">// ./node_modules/pkg/index.cjs\nconst state = require('./state.cjs');\nmodule.exports.state = state;\n</code></pre>\n<pre><code class=\"language-js\">// ./node_modules/pkg/index.mjs\nimport state from './state.cjs';\nexport {\n state\n};\n</code></pre>\n<p>Even if <code>pkg</code> is used via both <code>require</code> and <code>import</code> in an application (for\nexample, via <code>import</code> in application code and via <code>require</code> by a dependency)\neach reference of <code>pkg</code> will contain the same state; and modifying that\nstate from either module system will apply to both.</p>\n</li>\n</ol>\n<p>Any plugins that attach to the package’s singleton would need to separately\nattach to both the CommonJS and ES module singletons.</p>\n<p>This approach is appropriate for any of the following use cases:</p>\n<ul>\n<li>The package is currently written in ES module syntax and the package author\nwants that version to be used wherever such syntax is supported.</li>\n<li>The package is stateless or its state can be isolated without too much\ndifficulty.</li>\n<li>The package is unlikely to have other public packages that depend on it, or if\nit does, the package is stateless or has state that need not be shared between\ndependencies or with the overall application.</li>\n</ul>\n<p>Even with isolated state, there is still the cost of possible extra code\nexecution between the CommonJS and ES module versions of a package.</p>\n<p>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<code>\"./module\"</code>, to point to an all-ES module-syntax version of the package:</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">// ./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</code></pre>",
"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": "<p>The <em>specifier</em> of an <code>import</code> statement is the string after the <code>from</code> keyword,\ne.g. <code>'path'</code> in <code>import { sep } from 'path'</code>. Specifiers are also used in\n<code>export from</code> statements, and as the argument to an <code>import()</code> expression.</p>\n<p>There are four types of specifiers:</p>\n<ul>\n<li>\n<p><em>Bare specifiers</em> like <code>'some-package'</code>. They refer to an entry point of a\npackage by the package name.</p>\n</li>\n<li>\n<p><em>Deep import specifiers</em> like <code>'some-package/lib/shuffle.mjs'</code>. They refer to\na path within a package prefixed by the package name.</p>\n</li>\n<li>\n<p><em>Relative specifiers</em> like <code>'./startup.js'</code> or <code>'../config.mjs'</code>. They refer\nto a path relative to the location of the importing file.</p>\n</li>\n<li>\n<p><em>Absolute specifiers</em> like <code>'file:///opt/nodejs/config.js'</code>. They refer\ndirectly and explicitly to a full path.</p>\n</li>\n</ul>\n<p>Bare specifiers, and the bare specifier portion of deep import specifiers, are\nstrings; but everything else in a specifier is a URL.</p>\n<p>Only <code>file:</code> and <code>data:</code> URLs are supported. A specifier like\n<code>'https://example.com/app.js'</code> may be supported by browsers but it is not\nsupported in Node.js.</p>\n<p>Specifiers may not begin with <code>/</code> or <code>//</code>. These are reserved for potential\nfuture use. The root of the current volume may be referenced via <code>file:///</code>.</p>",
"modules": [
{
"textRaw": "`data:` Imports",
"name": "`data:`_imports",
"meta": {
"added": [
"v12.10.0"
],
"changes": []
},
"desc": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs\"><code>data:</code> URLs</a> are supported for importing with the following MIME types:</p>\n<ul>\n<li><code>text/javascript</code> for ES Modules</li>\n<li><code>application/json</code> for JSON</li>\n<li><code>application/wasm</code> for WASM.</li>\n</ul>\n<p><code>data:</code> URLs only resolve <a href=\"#esm_terminology\"><em>Bare specifiers</em></a> for builtin modules\nand <a href=\"#esm_terminology\"><em>Absolute specifiers</em></a>. Resolving\n<a href=\"#esm_terminology\"><em>Relative specifiers</em></a> will not work because <code>data:</code> is not a\n<a href=\"https://url.spec.whatwg.org/#special-scheme\">special scheme</a>. For example, attempting to load <code>./foo</code>\nfrom <code>data:text/javascript,import \"./foo\";</code> will fail to resolve since there\nis no concept of relative resolution for <code>data:</code> URLs. An example of a <code>data:</code>\nURLs being used is:</p>\n<pre><code class=\"language-js\">import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"';\n</code></pre>",
"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": "<p>A file extension must be provided when using the <code>import</code> keyword. Directory\nindexes (e.g. <code>'./startup/index.js'</code>) must also be fully specified.</p>\n<p>This behavior matches how <code>import</code> behaves in browser environments, assuming a\ntypically configured server.</p>",
"type": "module",
"displayName": "Mandatory file extensions"
},
{
"textRaw": "No `NODE_PATH`",
"name": "no_`node_path`",
"desc": "<p><code>NODE_PATH</code> is not part of resolving <code>import</code> specifiers. Please use symlinks\nif this behavior is desired.</p>",
"type": "module",
"displayName": "No `NODE_PATH`"
},
{
"textRaw": "No `require`, `exports`, `module.exports`, `__filename`, `__dirname`",
"name": "no_`require`,_`exports`,_`module.exports`,_`__filename`,_`__dirname`",
"desc": "<p>These CommonJS variables are not available in ES modules.</p>\n<p><code>require</code> can be imported into an ES module using <a href=\"modules.html#modules_module_createrequire_filename\"><code>module.createRequire()</code></a>.</p>\n<p>Equivalents of <code>__filename</code> and <code>__dirname</code> can be created inside of each file\nvia <a href=\"#esm_import_meta\"><code>import.meta.url</code></a>.</p>\n<pre><code class=\"language-js\">import { fileURLToPath } from 'url';\nimport { dirname } from 'path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n</code></pre>",
"type": "module",
"displayName": "No `require`, `exports`, `module.exports`, `__filename`, `__dirname`"
},
{
"textRaw": "No `require.resolve`",
"name": "no_`require.resolve`",
"desc": "<p>Former use cases relying on <code>require.resolve</code> to determine the resolved path\nof a module can be supported via <code>import.meta.resolve</code>, which is experimental\nand supported via the <code>--experimental-import-meta-resolve</code> flag:</p>\n<pre><code class=\"language-js\">(async () => {\n const dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n})();\n</code></pre>\n<p><code>import.meta.resolve</code> also accepts a second argument which is the parent module\nfrom which to resolve from:</p>\n<pre><code class=\"language-js\">(async () => {\n // Equivalent to import.meta.resolve('./dep')\n await import.meta.resolve('./dep', import.meta.url);\n})();\n</code></pre>\n<p>This function is asynchronous since the ES module resolver in Node.js is\nasynchronous. With the introduction of <a href=\"https://github.com/tc39/proposal-top-level-await\">Top-Level Await</a>, these use cases\nwill be easier as they won't require an async function wrapper.</p>",
"type": "module",
"displayName": "No `require.resolve`"
},
{
"textRaw": "No `require.extensions`",
"name": "no_`require.extensions`",
"desc": "<p><code>require.extensions</code> is not used by <code>import</code>. The expectation is that loader\nhooks can provide this workflow in the future.</p>",
"type": "module",
"displayName": "No `require.extensions`"
},
{
"textRaw": "No `require.cache`",
"name": "no_`require.cache`",
"desc": "<p><code>require.cache</code> is not used by <code>import</code>. It has a separate cache.</p>",
"type": "module",
"displayName": "No `require.cache`"
},
{
"textRaw": "URL-based paths",
"name": "url-based_paths",
"desc": "<p>ES modules are resolved and cached based upon\n<a href=\"https://url.spec.whatwg.org/\">URL</a> semantics. This means that files containing\nspecial characters such as <code>#</code> and <code>?</code> need to be escaped.</p>\n<p>Modules will be loaded multiple times if the <code>import</code> specifier used to resolve\nthem have a different query or fragment.</p>\n<pre><code class=\"language-js\">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</code></pre>\n<p>For now, only modules using the <code>file:</code> protocol can be loaded.</p>",
"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": "<p><code>require</code> always treats the files it references as CommonJS. This applies\nwhether <code>require</code> is used the traditional way within a CommonJS environment, or\nin an ES module environment using <a href=\"modules.html#modules_module_createrequire_filename\"><code>module.createRequire()</code></a>.</p>\n<p>To include an ES module into CommonJS, use <a href=\"#esm_import_expressions\"><code>import()</code></a>.</p>",
"type": "module",
"displayName": "`require`"
},
{
"textRaw": "`import` statements",
"name": "`import`_statements",
"desc": "<p>An <code>import</code> 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\n<a href=\"modules.html#modules_module_createrequire_filename\"><code>module.createRequire()</code></a>.</p>\n<p><code>import</code> statements are permitted only in ES modules. For similar functionality\nin CommonJS, see <a href=\"#esm_import_expressions\"><code>import()</code></a>.</p>\n<p>The <em>specifier</em> of an <code>import</code> statement (the string after the <code>from</code> keyword)\ncan either be an URL-style relative path like <code>'./file.mjs'</code> or a package name\nlike <code>'fs'</code>.</p>\n<p>Like in CommonJS, files within packages can be accessed by appending a path to\nthe package name; unless the package’s <code>package.json</code> contains an <code>\"exports\"</code>\nfield, in which case files within packages need to be accessed via the path\ndefined in <code>\"exports\"</code>.</p>\n<pre><code class=\"language-js\">import { sin, cos } from 'geometry/trigonometry-functions.mjs';\n</code></pre>\n<p>Only the “default export” is supported for CommonJS files or packages:</p>\n<!-- eslint-disable no-duplicate-imports -->\n<pre><code class=\"language-js\">import packageMain from 'commonjs-package'; // Works\n\nimport { method } from 'commonjs-package'; // Errors\n</code></pre>\n<p>It is also possible to\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_a_module_for_its_side_effects_only\">import an ES or CommonJS module for its side effects only</a>.</p>",
"type": "module",
"displayName": "`import` statements"
},
{
"textRaw": "`import()` expressions",
"name": "`import()`_expressions",
"desc": "<p><a href=\"https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports\">Dynamic <code>import()</code></a> is supported in both CommonJS and ES modules. It can be\nused to include ES module files from CommonJS code.</p>",
"type": "module",
"displayName": "`import()` expressions"
}
],
"type": "misc",
"displayName": "Interoperability with CommonJS"
},
{
"textRaw": "CommonJS, JSON, and native modules",
"name": "commonjs,_json,_and_native_modules",
"desc": "<p>CommonJS, JSON, and native modules can be used with\n<a href=\"modules.html#modules_module_createrequire_filename\"><code>module.createRequire()</code></a>.</p>\n<pre><code class=\"language-js\">// 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</code></pre>",
"type": "misc",
"displayName": "CommonJS, JSON, and native modules"
},
{
"textRaw": "Builtin modules",
"name": "builtin_modules",
"desc": "<p>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\n<a href=\"modules.html#modules_module_syncbuiltinesmexports\"><code>module.syncBuiltinESMExports()</code></a>.</p>\n<pre><code class=\"language-js\">import EventEmitter from 'events';\nconst e = new EventEmitter();\n</code></pre>\n<pre><code class=\"language-js\">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</code></pre>\n<pre><code class=\"language-js\">import fs, { readFileSync } from 'fs';\nimport { syncBuiltinESMExports } from 'module';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;\n</code></pre>",
"type": "misc",
"displayName": "Builtin modules"
},
{
"textRaw": "Experimental JSON modules",
"name": "experimental_json_modules",
"desc": "<p>Currently importing JSON modules are only supported in the <code>commonjs</code> mode\nand are loaded using the CJS loader. <a href=\"https://html.spec.whatwg.org/#creating-a-json-module-script\">WHATWG JSON modules specification</a> are\nstill being standardized, and are experimentally supported by including the\nadditional flag <code>--experimental-json-modules</code> when running Node.js.</p>\n<p>When the <code>--experimental-json-modules</code> flag is included both the\n<code>commonjs</code> and <code>module</code> mode will use the new experimental JSON\nloader. The imported JSON only exposes a <code>default</code>, 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.</p>\n<p>Assuming an <code>index.mjs</code> with</p>\n<!-- eslint-skip -->\n<pre><code class=\"language-js\">import packageConfig from './package.json';\n</code></pre>\n<p>The <code>--experimental-json-modules</code> flag is needed for the module\nto work.</p>\n<pre><code class=\"language-bash\">node index.mjs # fails\nnode --experimental-json-modules index.mjs # works\n</code></pre>",
"type": "misc",
"displayName": "Experimental JSON modules"
},
{
"textRaw": "Experimental Wasm modules",
"name": "experimental_wasm_modules",
"desc": "<p>Importing Web Assembly modules is supported under the\n<code>--experimental-wasm-modules</code> flag, allowing any <code>.wasm</code> files to be\nimported as normal modules while also supporting their module imports.</p>\n<p>This integration is in line with the\n<a href=\"https://github.com/webassembly/esm-integration\">ES Module Integration Proposal for Web Assembly</a>.</p>\n<p>For example, an <code>index.mjs</code> containing:</p>\n<pre><code class=\"language-js\">import * as M from './module.wasm';\nconsole.log(M);\n</code></pre>\n<p>executed under:</p>\n<pre><code class=\"language-bash\">node --experimental-wasm-modules index.mjs\n</code></pre>\n<p>would provide the exports interface for the instantiation of <code>module.wasm</code>.</p>",
"type": "misc",
"displayName": "Experimental Wasm modules"
},
{
"textRaw": "Experimental loaders",
"name": "Experimental loaders",
"type": "misc",
"desc": "<p><strong>Note: This API is currently being redesigned and will still change.</strong></p>\n<p>To customize the default module resolution, loader hooks can optionally be\nprovided via a <code>--experimental-loader ./loader-name.mjs</code> argument to Node.js.</p>\n<p>When hooks are used they only apply to ES module loading and not to any\nCommonJS modules loaded.</p>",
"miscs": [
{
"textRaw": "Hooks",
"name": "hooks",
"modules": [
{
"textRaw": "<code>resolve</code> hook",
"name": "<code>resolve</code>_hook",
"desc": "<blockquote>\n<p>Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.</p>\n</blockquote>\n<p>The <code>resolve</code> hook returns the resolved file URL for a given module specifier\nand parent URL. The module specifier is the string in an <code>import</code> statement or\n<code>import()</code> expression, and the parent URL is the URL of the module that imported\nthis one, or <code>undefined</code> if this is the main entry point for the application.</p>\n<p>The <code>conditions</code> property on the <code>context</code> is an array of conditions for\n<a href=\"#esm_conditional_exports\">Conditional exports</a> 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.</p>\n<p>The <a href=\"#esm_conditional_exports\">current set of Node.js default conditions</a> will always\nbe in the <code>context.conditions</code> list passed to the hook. If the hook wants to\nensure Node.js-compatible resolution logic, all items from this default\ncondition list <strong>must</strong> be passed through to the <code>defaultResolve</code> function.</p>\n<pre><code class=\"language-js\">/**\n * @param {string} specifier\n * @param {{\n * parentURL: !(string | undefined),\n * conditions: !(Array<string>),\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</code></pre>",
"type": "module",
"displayName": "<code>resolve</code> hook"
},
{
"textRaw": "<code>getFormat</code> hook",
"name": "<code>getformat</code>_hook",
"desc": "<blockquote>\n<p>Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.</p>\n</blockquote>\n<p>The <code>getFormat</code> hook provides a way to define a custom method of determining how\na URL should be interpreted. The <code>format</code> returned also affects what the\nacceptable forms of source values are for a module when parsing. This can be one\nof the following:</p>\n<table>\n<thead>\n<tr>\n<th><code>format</code></th>\n<th>Description</th>\n<th>Acceptable Types For <code>source</code> Returned by <code>getSource</code> or <code>transformSource</code></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>'builtin'</code></td>\n<td>Load a Node.js builtin module</td>\n<td>Not applicable</td>\n</tr>\n<tr>\n<td><code>'commonjs'</code></td>\n<td>Load a Node.js CommonJS module</td>\n<td>Not applicable</td>\n</tr>\n<tr>\n<td><code>'dynamic'</code></td>\n<td>Use a <a href=\"#esm_code_dynamicinstantiate_code_hook\">dynamic instantiate hook</a></td>\n<td>Not applicable</td>\n</tr>\n<tr>\n<td><code>'json'</code></td>\n<td>Load a JSON file</td>\n<td>{ <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-constructor\">ArrayBuffer</a>, <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-string-constructor\">string</a>, <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-typedarray-objects\">TypedArray</a> }</td>\n</tr>\n<tr>\n<td><code>'module'</code></td>\n<td>Load an ES module</td>\n<td>{ <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-constructor\">ArrayBuffer</a>, <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-string-constructor\">string</a>, <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-typedarray-objects\">TypedArray</a> }</td>\n</tr>\n<tr>\n<td><code>'wasm'</code></td>\n<td>Load a WebAssembly module</td>\n<td>{ <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-constructor\">ArrayBuffer</a>, <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-string-constructor\">string</a>, <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-typedarray-objects\">TypedArray</a> }</td>\n</tr>\n</tbody>\n</table>\n<p>Note: These types all correspond to classes defined in ECMAScript.</p>\n<ul>\n<li>The specific <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-constructor\">ArrayBuffer</a> object is a <a href=\"https://tc39.es/ecma262/#sec-sharedarraybuffer-constructor\">SharedArrayBuffer</a>.</li>\n<li>The specific <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-string-constructor\">string</a> object is not the class constructor, but an instance.</li>\n<li>The specific <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-typedarray-objects\">TypedArray</a> object is a <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-uint8array\">Uint8Array</a>.</li>\n</ul>\n<p>Note: If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>) is\nnot a string, it will be converted to a string using <a href=\"util.html#util_class_util_textdecoder\"><code>util.TextDecoder</code></a>.</p>\n<pre><code class=\"language-js\">/**\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</code></pre>",
"type": "module",
"displayName": "<code>getFormat</code> hook"
},
{
"textRaw": "<code>getSource</code> hook",
"name": "<code>getsource</code>_hook",
"desc": "<blockquote>\n<p>Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.</p>\n</blockquote>\n<p>The <code>getSource</code> 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.</p>\n<pre><code class=\"language-js\">/**\n * @param {string} url\n * @param {{ format: string }} context\n * @param {Function} defaultGetSource\n * @returns {Promise<{ source: !(SharedArrayBuffer | string | 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</code></pre>",
"type": "module",
"displayName": "<code>getSource</code> hook"
},
{
"textRaw": "<code>transformSource</code> hook",
"name": "<code>transformsource</code>_hook",
"desc": "<pre><code class=\"language-console\">NODE_OPTIONS='--experimental-loader ./custom-loader.mjs' node x.js\n</code></pre>\n<blockquote>\n<p>Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.</p>\n</blockquote>\n<p>The <code>transformSource</code> 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.</p>\n<p>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 <a href=\"#esm_transpiler_loader\">transpiler loader example</a> below.</p>\n<pre><code class=\"language-js\">/**\n * @param {!(SharedArrayBuffer | string | Uint8Array)} source\n * @param {{\n * url: string,\n * format: string,\n * }} context\n * @param {Function} defaultTransformSource\n * @returns {Promise<{ source: !(SharedArrayBuffer | string | 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</code></pre>",
"type": "module",
"displayName": "<code>transformSource</code> hook"
},
{
"textRaw": "<code>getGlobalPreloadCode</code> hook",
"name": "<code>getglobalpreloadcode</code>_hook",
"desc": "<blockquote>\n<p>Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.</p>\n</blockquote>\n<p>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.</p>\n<p>Similar to how CommonJS wrappers work, the code runs in an implicit function\nscope. The only argument is a <code>require</code>-like function that can be used to load\nbuiltins like \"fs\": <code>getBuiltin(request: string)</code>.</p>\n<p>If the code needs more advanced <code>require</code> features, it will have to construct\nits own <code>require</code> using <code>module.createRequire()</code>.</p>\n<pre><code class=\"language-js\">/**\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</code></pre>",
"type": "module",
"displayName": "<code>getGlobalPreloadCode</code> hook"
},
{
"textRaw": "<code>dynamicInstantiate</code> hook",
"name": "<code>dynamicinstantiate</code>_hook",
"desc": "<blockquote>\n<p>Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.</p>\n</blockquote>\n<p>To create a custom dynamic module that doesn't correspond to one of the\nexisting <code>format</code> interpretations, the <code>dynamicInstantiate</code> hook can be used.\nThis hook is called only for modules that return <code>format: 'dynamic'</code> from\nthe <a href=\"#esm_code_getformat_code_hook\"><code>getFormat</code> hook</a>.</p>\n<pre><code class=\"language-js\">/**\n * @param {string} url\n * @returns {object} response\n * @returns {array} response.exports\n * @returns {function} response.execute\n */\nexport async function dynamicInstantiate(url) {\n return {\n exports: ['customExportName'],\n execute: (exports) => {\n // Get and set functions provided for pre-allocated export names\n exports.customExportName.set('value');\n }\n };\n}\n</code></pre>\n<p>With the list of module exports provided upfront, the <code>execute</code> function will\nthen be called at the exact point of module evaluation order for that module\nin the import tree.</p>\n<h3>Examples</h3>\n<p>The various loader hooks can be used together to accomplish wide-ranging\ncustomizations of Node.js’ code loading and evaluation behaviors.</p>",
"type": "module",
"displayName": "<code>dynamicInstantiate</code> hook"
},
{
"textRaw": "HTTPS loader",
"name": "https_loader",
"desc": "<p>In current Node.js, specifiers starting with <code>https://</code> 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.</p>\n<pre><code class=\"language-js\">// 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</code></pre>\n<pre><code class=\"language-js\">// main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n</code></pre>\n<p>With this loader, running:</p>\n<pre><code class=\"language-console\">node --experimental-loader ./https-loader.mjs ./main.js\n</code></pre>\n<p>Will print the current version of CoffeeScript per the module at the URL in\n<code>main.mjs</code>.</p>",
"type": "module",
"displayName": "HTTPS loader"
},
{
"textRaw": "Transpiler loader",
"name": "transpiler_loader",
"desc": "<p>Sources that are in formats Node.js doesn’t understand can be converted into\nJavaScript using the <a href=\"#esm_code_transformsource_code_hook\"><code>transformSource</code> hook</a>. 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.</p>\n<p>This is less performant than transpiling source files before running\nNode.js; a transpiler loader should only be used for development and testing\npurposes.</p>\n<pre><code class=\"language-js\">// 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</code></pre>\n<pre><code class=\"language-coffee\"># 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</code></pre>\n<pre><code class=\"language-coffee\"># scream.coffee\nexport scream = (str) -> str.toUpperCase()\n</code></pre>\n<p>With this loader, running:</p>\n<pre><code class=\"language-console\">node --experimental-loader ./coffeescript-loader.mjs main.coffee\n</code></pre>\n<p>Will cause <code>main.coffee</code> to be turned into JavaScript after its source code is\nloaded from disk but before Node.js executes it; and so on for any <code>.coffee</code>,\n<code>.litcoffee</code> or <code>.coffee.md</code> files referenced via <code>import</code> statements of any\nloaded file.</p>",
"type": "module",
"displayName": "Transpiler loader"
}
],
"type": "misc",
"displayName": "Hooks"
}
]
},
{
"textRaw": "Resolution algorithm",
"name": "resolution_algorithm",
"modules": [
{
"textRaw": "Features",
"name": "features",
"desc": "<p>The resolver has the following properties:</p>\n<ul>\n<li>FileURL-based resolution as is used by ES modules</li>\n<li>Support for builtin module loading</li>\n<li>Relative and absolute URL resolution</li>\n<li>No default extensions</li>\n<li>No folder mains</li>\n<li>Bare specifier package resolution lookup through node_modules</li>\n</ul>",
"type": "module",
"displayName": "Features"
},
{
"textRaw": "Resolver algorithm",
"name": "resolver_algorithm",
"desc": "<p>The algorithm to load an ES module specifier is given through the\n<strong>ESM_RESOLVE</strong> method below. It returns the resolved URL for a\nmodule specifier relative to a parentURL.</p>\n<p>The algorithm to determine the module format of a resolved URL is\nprovided by <strong>ESM_FORMAT</strong>, which returns the unique module\nformat for any file. The <em>\"module\"</em> format is returned for an ECMAScript\nModule, while the <em>\"commonjs\"</em> format is used to indicate loading through the\nlegacy CommonJS loader. Additional formats such as <em>\"addon\"</em> can be extended in\nfuture updates.</p>\n<p>In the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.</p>\n<p><em>defaultEnv</em> is the conditional environment name priority array,\n<code>[\"node\", \"import\"]</code>.</p>\n<p>The resolver can throw the following errors:</p>\n<ul>\n<li><em>Invalid Module Specifier</em>: Module specifier is an invalid URL, package name\nor package subpath specifier.</li>\n<li><em>Invalid Package Configuration</em>: package.json configuration is invalid or\ncontains an invalid configuration.</li>\n<li><em>Invalid Package Target</em>: Package exports define a target module within the\npackage that is an invalid type or string target.</li>\n<li><em>Package Path Not Exported</em>: Package exports do not define or permit a target\nsubpath in the package for the given module.</li>\n<li><em>Module Not Found</em>: The package or module requested does not exist.</li>\n</ul>\n<details>\n<summary>Resolver algorithm specification</summary>\n<p><strong>ESM_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>)</p>\n<blockquote>\n<ol>\n<li>Let <em>resolvedURL</em> be <strong>undefined</strong>.</li>\n<li>\n<p>If <em>specifier</em> is a valid URL, then</p>\n<ol>\n<li>Set <em>resolvedURL</em> to the result of parsing and reserializing\n<em>specifier</em> as a URL.</li>\n</ol>\n</li>\n<li>\n<p>Otherwise, if <em>specifier</em> starts with <em>\"/\"</em>, then</p>\n<ol>\n<li>Throw an <em>Invalid Module Specifier</em> error.</li>\n</ol>\n</li>\n<li>\n<p>Otherwise, if <em>specifier</em> starts with <em>\"./\"</em> or <em>\"../\"</em>, then</p>\n<ol>\n<li>Set <em>resolvedURL</em> to the URL resolution of <em>specifier</em> relative to\n<em>parentURL</em>.</li>\n</ol>\n</li>\n<li>\n<p>Otherwise,</p>\n<ol>\n<li>Note: <em>specifier</em> is now a bare specifier.</li>\n<li>Set <em>resolvedURL</em> the result of\n<strong>PACKAGE_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>).</li>\n</ol>\n</li>\n<li>\n<p>If <em>resolvedURL</em> contains any percent encodings of <em>\"/\"</em> or <em>\"\\\"</em> (<em>\"%2f\"</em>\nand <em>\"%5C\"</em> respectively), then</p>\n<ol>\n<li>Throw an <em>Invalid Module Specifier</em> error.</li>\n</ol>\n</li>\n<li>\n<p>If the file at <em>resolvedURL</em> is a directory, then</p>\n<ol>\n<li>Throw an <em>Unsupported Directory Import</em> error.</li>\n</ol>\n</li>\n<li>\n<p>If the file at <em>resolvedURL</em> does not exist, then</p>\n<ol>\n<li>Throw a <em>Module Not Found</em> error.</li>\n</ol>\n</li>\n<li>Set <em>resolvedURL</em> to the real path of <em>resolvedURL</em>.</li>\n<li>Let <em>format</em> be the result of <strong>ESM_FORMAT</strong>(<em>resolvedURL</em>).</li>\n<li>Load <em>resolvedURL</em> as module format, <em>format</em>.</li>\n<li>Return <em>resolvedURL</em>.</li>\n</ol>\n</blockquote>\n<p><strong>PACKAGE_RESOLVE</strong>(<em>packageSpecifier</em>, <em>parentURL</em>)</p>\n<blockquote>\n<ol>\n<li>Let <em>packageName</em> be <em>undefined</em>.</li>\n<li>Let <em>packageSubpath</em> be <em>undefined</em>.</li>\n<li>\n<p>If <em>packageSpecifier</em> is an empty string, then</p>\n<ol>\n<li>Throw an <em>Invalid Module Specifier</em> error.</li>\n</ol>\n</li>\n<li>\n<p>Otherwise,</p>\n<ol>\n<li>\n<p>If <em>packageSpecifier</em> does not contain a <em>\"/\"</em> separator, then</p>\n<ol>\n<li>Throw an <em>Invalid Module Specifier</em> error.</li>\n</ol>\n</li>\n<li>Set <em>packageName</em> to the substring of <em>packageSpecifier</em>\nuntil the second <em>\"/\"</em> separator or the end of the string.</li>\n</ol>\n</li>\n<li>\n<p>If <em>packageName</em> starts with <em>\".\"</em> or contains <em>\"\\\"</em> or <em>\"%\"</em>, then</p>\n<ol>\n<li>Throw an <em>Invalid Module Specifier</em> error.</li>\n</ol>\n</li>\n<li>Let <em>packageSubpath</em> be <em>undefined</em>.</li>\n<li>\n<p>If the length of <em>packageSpecifier</em> is greater than the length of\n<em>packageName</em>, then</p>\n<ol>\n<li>Set <em>packageSubpath</em> to <em>\".\"</em> concatenated with the substring of\n<em>packageSpecifier</em> from the position at the length of <em>packageName</em>.</li>\n</ol>\n</li>\n<li>\n<p>If <em>packageSubpath</em> contains any <em>\".\"</em> or <em>\"..\"</em> segments or percent\nencoded strings for <em>\"/\"</em> or <em>\"\\\"</em>, then</p>\n<ol>\n<li>Throw an <em>Invalid Module Specifier</em> error.</li>\n</ol>\n</li>\n<li>Set <em>selfUrl</em> to the result of\n<strong>SELF_REFERENCE_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>).</li>\n<li>If <em>selfUrl</em> isn't empty, return <em>selfUrl</em>.</li>\n<li>\n<p>If <em>packageSubpath</em> is <em>undefined</em> and <em>packageName</em> is a Node.js builtin\nmodule, then</p>\n<ol>\n<li>Return the string <em>\"nodejs:\"</em> concatenated with <em>packageSpecifier</em>.</li>\n</ol>\n</li>\n<li>\n<p>While <em>parentURL</em> is not the file system root,</p>\n<ol>\n<li>Let <em>packageURL</em> be the URL resolution of <em>\"node_modules/\"</em>\nconcatenated with <em>packageSpecifier</em>, relative to <em>parentURL</em>.</li>\n<li>Set <em>parentURL</em> to the parent folder URL of <em>parentURL</em>.</li>\n<li>\n<p>If the folder at <em>packageURL</em> does not exist, then</p>\n<ol>\n<li>Set <em>parentURL</em> to the parent URL path of <em>parentURL</em>.</li>\n<li>Continue the next loop iteration.</li>\n</ol>\n</li>\n<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>\n<li>\n<p>If <em>packageSubpath</em> is equal to <em>\"./\"</em>, then</p>\n<ol>\n<li>Return <em>packageURL</em> + <em>\"/\"</em>.</li>\n</ol>\n</li>\n<li>\n<p>If <em>packageSubpath</em> is _undefined__, then</p>\n<ol>\n<li>Return the result of <strong>PACKAGE_MAIN_RESOLVE</strong>(<em>packageURL</em>,\n<em>pjson</em>).</li>\n</ol>\n</li>\n<li>\n<p>Otherwise,</p>\n<ol>\n<li>\n<p>If <em>pjson</em> is not <strong>null</strong> and <em>pjson</em> has an <em>\"exports\"</em> key, then</p>\n<ol>\n<li>Let <em>exports</em> be <em>pjson.exports</em>.</li>\n<li>\n<p>If <em>exports</em> is not <strong>null</strong> or <strong>undefined</strong>, then</p>\n<ol>\n<li>Return <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>,\n<em>packageSubpath</em>, <em>pjson.exports</em>).</li>\n</ol>\n</li>\n</ol>\n</li>\n<li>Return the URL resolution of <em>packageSubpath</em> in <em>packageURL</em>.</li>\n</ol>\n</li>\n</ol>\n</li>\n<li>Throw a <em>Module Not Found</em> error.</li>\n</ol>\n</blockquote>\n<p><strong>SELF_REFERENCE_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>)</p>\n<blockquote>\n<ol>\n<li>Let <em>packageURL</em> be the result of <strong>READ_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li>\n<li>\n<p>If <em>packageURL</em> is <strong>null</strong>, then</p>\n<ol>\n<li>Return <strong>undefined</strong>.</li>\n</ol>\n</li>\n<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>\n<li>\n<p>If <em>pjson</em> does not include an <em>\"exports\"</em> property, then</p>\n<ol>\n<li>Return <strong>undefined</strong>.</li>\n</ol>\n</li>\n<li>\n<p>If <em>pjson.name</em> is equal to <em>packageName</em>, then</p>\n<ol>\n<li>\n<p>If <em>packageSubpath</em> is equal to <em>\"./\"</em>, then</p>\n<ol>\n<li>Return <em>packageURL</em> + <em>\"/\"</em>.</li>\n</ol>\n</li>\n<li>\n<p>If <em>packageSubpath</em> is <em>undefined</em>, then</p>\n<ol>\n<li>Return the result of <strong>PACKAGE_MAIN_RESOLVE</strong>(<em>packageURL</em>, <em>pjson</em>).</li>\n</ol>\n</li>\n<li>\n<p>Otherwise,</p>\n<ol>\n<li>\n<p>If <em>pjson</em> is not <strong>null</strong> and <em>pjson</em> has an <em>\"exports\"</em> key, then</p>\n<ol>\n<li>Let <em>exports</em> be <em>pjson.exports</em>.</li>\n<li>\n<p>If <em>exports</em> is not <strong>null</strong> or <strong>undefined</strong>, then</p>\n<ol>\n<li>Return <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>subpath</em>,\n<em>pjson.exports</em>).</li>\n</ol>\n</li>\n</ol>\n</li>\n<li>Return the URL resolution of <em>subpath</em> in <em>packageURL</em>.</li>\n</ol>\n</li>\n</ol>\n</li>\n<li>Otherwise, return <strong>undefined</strong>.</li>\n</ol>\n</blockquote>\n<p><strong>PACKAGE_MAIN_RESOLVE</strong>(<em>packageURL</em>, <em>pjson</em>)</p>\n<blockquote>\n<ol>\n<li>\n<p>If <em>pjson</em> is <strong>null</strong>, then</p>\n<ol>\n<li>Throw a <em>Module Not Found</em> error.</li>\n</ol>\n</li>\n<li>\n<p>If <em>pjson.exports</em> is not <strong>null</strong> or <strong>undefined</strong>, then</p>\n<ol>\n<li>If <em>exports</em> is an Object with both a key starting with <em>\".\"</em> and a key\nnot starting with <em>\".\"</em>, throw an <em>Invalid Package Configuration</em> error.</li>\n<li>\n<p>If <em>pjson.exports</em> is a String or Array, or an Object containing no\nkeys starting with <em>\".\"</em>, then</p>\n<ol>\n<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>,\n<em>pjson.exports</em>, <em>\"\"</em>).</li>\n</ol>\n</li>\n<li>\n<p>If <em>pjson.exports</em> is an Object containing a <em>\".\"</em> property, then</p>\n<ol>\n<li>Let <em>mainExport</em> be the <em>\".\"</em> property in <em>pjson.exports</em>.</li>\n<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>,\n<em>mainExport</em>, <em>\"\"</em>).</li>\n</ol>\n</li>\n<li>Throw a <em>Package Path Not Exported</em> error.</li>\n</ol>\n</li>\n<li>Let <em>legacyMainURL</em> be the result applying the legacy\n<strong>LOAD_AS_DIRECTORY</strong> CommonJS resolver to <em>packageURL</em>, throwing a\n<em>Module Not Found</em> error for no resolution.</li>\n<li>Return <em>legacyMainURL</em>.</li>\n</ol>\n</blockquote>\n<p><strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>packagePath</em>, <em>exports</em>)</p>\n<blockquote>\n<ol>\n<li>If <em>exports</em> is an Object with both a key starting with <em>\".\"</em> and a key not\nstarting with <em>\".\"</em>, throw an <em>Invalid Package Configuration</em> error.</li>\n<li>\n<p>If <em>exports</em> is an Object and all keys of <em>exports</em> start with <em>\".\"</em>, then</p>\n<ol>\n<li>Set <em>packagePath</em> to <em>\"./\"</em> concatenated with <em>packagePath</em>.</li>\n<li>\n<p>If <em>packagePath</em> is a key of <em>exports</em>, then</p>\n<ol>\n<li>Let <em>target</em> be the value of <em>exports[packagePath]</em>.</li>\n<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>,\n<em>\"\"</em>, <em>defaultEnv</em>).</li>\n</ol>\n</li>\n<li>Let <em>directoryKeys</em> be the list of keys of <em>exports</em> ending in\n<em>\"/\"</em>, sorted by length descending.</li>\n<li>\n<p>For each key <em>directory</em> in <em>directoryKeys</em>, do</p>\n<ol>\n<li>\n<p>If <em>packagePath</em> starts with <em>directory</em>, then</p>\n<ol>\n<li>Let <em>target</em> be the value of <em>exports[directory]</em>.</li>\n<li>Let <em>subpath</em> be the substring of <em>target</em> starting at the index\nof the length of <em>directory</em>.</li>\n<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>,\n<em>subpath</em>, <em>defaultEnv</em>).</li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n</li>\n<li>Throw a <em>Package Path Not Exported</em> error.</li>\n</ol>\n</blockquote>\n<p><strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>, <em>subpath</em>, <em>env</em>)</p>\n<blockquote>\n<ol>\n<li>\n<p>If <em>target</em> is a String, then</p>\n<ol>\n<li>If <em>target</em> does not start with <em>\"./\"</em> or contains any <em>\"node_modules\"</em>\nsegments including <em>\"node_modules\"</em> percent-encoding, throw an\n<em>Invalid Package Target</em> error.</li>\n<li>Let <em>resolvedTarget</em> be the URL resolution of the concatenation of\n<em>packageURL</em> and <em>target</em>.</li>\n<li>If <em>resolvedTarget</em> is not contained in <em>packageURL</em>, throw an\n<em>Invalid Package Target</em> error.</li>\n<li>If <em>subpath</em> has non-zero length and <em>target</em> does not end with <em>\"/\"</em>,\nthrow an <em>Invalid Module Specifier</em> error.</li>\n<li>Let <em>resolved</em> be the URL resolution of the concatenation of\n<em>subpath</em> and <em>resolvedTarget</em>.</li>\n<li>If <em>resolved</em> is not contained in <em>resolvedTarget</em>, throw an\n<em>Invalid Module Specifier</em> error.</li>\n<li>Return <em>resolved</em>.</li>\n</ol>\n</li>\n<li>\n<p>Otherwise, if <em>target</em> is a non-null Object, then</p>\n<ol>\n<li>If <em>exports</em> contains any index property keys, as defined in ECMA-262\n<a href=\"https://tc39.es/ecma262/#integer-index\">6.1.7 Array Index</a>, throw an <em>Invalid Package Configuration</em> error.</li>\n<li>\n<p>For each property <em>p</em> of <em>target</em>, in object insertion order as,</p>\n<ol>\n<li>\n<p>If <em>p</em> equals <em>\"default\"</em> or <em>env</em> contains an entry for <em>p</em>, then</p>\n<ol>\n<li>Let <em>targetValue</em> be the value of the <em>p</em> property in <em>target</em>.</li>\n<li>Return the result of <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(\n<em>packageURL</em>, <em>targetValue</em>, <em>subpath</em>, <em>env</em>), continuing the\nloop on any <em>Package Path Not Exported</em> error.</li>\n</ol>\n</li>\n</ol>\n</li>\n<li>Throw a <em>Package Path Not Exported</em> error.</li>\n</ol>\n</li>\n<li>\n<p>Otherwise, if <em>target</em> is an Array, then</p>\n<ol>\n<li>If <em>target.length is zero, throw a _Package Path Not Exported</em> error.</li>\n<li>\n<p>For each item <em>targetValue</em> in <em>target</em>, do</p>\n<ol>\n<li>If <em>targetValue</em> is an Array, continue the loop.</li>\n<li>Return the result of <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>,\n<em>targetValue</em>, <em>subpath</em>, <em>env</em>), continuing the loop on any\n<em>Package Path Not Exported</em> or <em>Invalid Package Target</em> error.</li>\n</ol>\n</li>\n<li>Throw the last fallback resolution error.</li>\n</ol>\n</li>\n<li>Otherwise, if <em>target</em> is <em>null</em>, throw a <em>Package Path Not Exported</em>\nerror.</li>\n<li>Otherwise throw an <em>Invalid Package Target</em> error.</li>\n</ol>\n</blockquote>\n<p><strong>ESM_FORMAT</strong>(<em>url</em>)</p>\n<blockquote>\n<ol>\n<li>Assert: <em>url</em> corresponds to an existing file.</li>\n<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_SCOPE</strong>(<em>url</em>).</li>\n<li>\n<p>If <em>url</em> ends in <em>\".mjs\"</em>, then</p>\n<ol>\n<li>Return <em>\"module\"</em>.</li>\n</ol>\n</li>\n<li>\n<p>If <em>url</em> ends in <em>\".cjs\"</em>, then</p>\n<ol>\n<li>Return <em>\"commonjs\"</em>.</li>\n</ol>\n</li>\n<li>\n<p>If <em>pjson?.type</em> exists and is <em>\"module\"</em>, then</p>\n<ol>\n<li>\n<p>If <em>url</em> ends in <em>\".js\"</em>, then</p>\n<ol>\n<li>Return <em>\"module\"</em>.</li>\n</ol>\n</li>\n<li>Throw an <em>Unsupported File Extension</em> error.</li>\n</ol>\n</li>\n<li>\n<p>Otherwise,</p>\n<ol>\n<li>Throw an <em>Unsupported File Extension</em> error.</li>\n</ol>\n</li>\n</ol>\n</blockquote>\n<p><strong>READ_PACKAGE_SCOPE</strong>(<em>url</em>)</p>\n<blockquote>\n<ol>\n<li>Let <em>scopeURL</em> be <em>url</em>.</li>\n<li>\n<p>While <em>scopeURL</em> is not the file system root,</p>\n<ol>\n<li>If <em>scopeURL</em> ends in a <em>\"node_modules\"</em> path segment, return <strong>null</strong>.</li>\n<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>scopeURL</em>).</li>\n<li>\n<p>If <em>pjson</em> is not <strong>null</strong>, then</p>\n<ol>\n<li>Return <em>pjson</em>.</li>\n</ol>\n</li>\n<li>Set <em>scopeURL</em> to the parent URL of <em>scopeURL</em>.</li>\n</ol>\n</li>\n<li>Return <strong>null</strong>.</li>\n</ol>\n</blockquote>\n<p><strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>)</p>\n<blockquote>\n<ol>\n<li>Let <em>pjsonURL</em> be the resolution of <em>\"package.json\"</em> within <em>packageURL</em>.</li>\n<li>\n<p>If the file at <em>pjsonURL</em> does not exist, then</p>\n<ol>\n<li>Return <strong>null</strong>.</li>\n</ol>\n</li>\n<li>\n<p>If the file at <em>packageURL</em> does not parse as valid JSON, then</p>\n<ol>\n<li>Throw an <em>Invalid Package Configuration</em> error.</li>\n</ol>\n</li>\n<li>Return the parsed JSON source of the file at <em>pjsonURL</em>.</li>\n</ol>\n</blockquote>\n</details>",
"type": "module",
"displayName": "Resolver algorithm"
},
{
"textRaw": "Customizing ESM specifier resolution algorithm",
"name": "customizing_esm_specifier_resolution_algorithm",
"desc": "<p>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.</p>\n<p>The <code>--experimental-specifier-resolution=[mode]</code> flag can be used to customize\nthe extension resolution algorithm. The default mode is <code>explicit</code>, 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 <code>node</code> mode.</p>\n<pre><code class=\"language-bash\">$ node index.mjs\nsuccess!\n$ node index # Failure!\nError: Cannot find module\n$ node --experimental-specifier-resolution=node index\nsuccess!\n</code></pre>",
"type": "module",
"displayName": "Customizing ESM specifier resolution algorithm"
}
],
"type": "misc",
"displayName": "Resolution algorithm"
}
],
"properties": [
{
"textRaw": "`meta` {Object}",
"type": "Object",
"name": "meta",
"desc": "<p>The <code>import.meta</code> metaproperty is an <code>Object</code> that contains the following\nproperty:</p>\n<ul>\n<li><code>url</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\"><string></a> The absolute <code>file:</code> URL of the module.</li>\n</ul>"
}
]
}
]
}