enclose-io/compiler

View on GitHub
lts/doc/api/esm.html

Summary

Maintainability
Test Coverage
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>ECMAScript modules | Node.js v12.18.3 Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/hljs.css">
  <link rel="canonical" href="https://nodejs.org/api/esm.html">
</head>
<body class="alt apidoc" id="api-section-esm">
  <div id="content" class="clearfix">
    <div id="column2" class="interior">
      <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
          Node.js
        </a>
      </div>
      <ul>
<li><a href="documentation.html" class="nav-documentation">About these docs</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with N-API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="esm.html" class="nav-esm active">ECMAScript modules</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
<li><a href="policy.html" class="nav-policy">Policies</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="report.html" class="nav-report">Report</a></li>
<li><a href="stream.html" class="nav-stream">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
</ul>
    </div>

    <div id="column1" data-id="esm" class="interior">
      <header>
        <h1>Node.js v12.18.3 Documentation</h1>
        <div id="gtoc">
          <ul>
            <li>
              <a href="index.html" name="toc">Index</a>
            </li>
            <li>
              <a href="all.html">View on single page</a>
            </li>
            <li>
              <a href="esm.json">View as JSON</a>
            </li>
            
    <li class="version-picker">
      <a href="#">View another version <span>&#x25bc;</span></a>
      <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v14.x/api/esm.html">14.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v13.x/api/esm.html">13.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v12.x/api/esm.html">12.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v11.x/api/esm.html">11.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v10.x/api/esm.html">10.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v9.x/api/esm.html">9.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v8.x/api/esm.html">8.x</a></li></ol>
    </li>
  
            <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/esm.md"><span class="github_icon"><svg height="16" width="16" viewBox="0 0 16.1 16.1" fill="currentColor"><path d="M8 0a8 8 0 0 0-2.5 15.6c.4 0 .5-.2.5-.4v-1.5c-2 .4-2.5-.5-2.7-1 0-.1-.5-.9-.8-1-.3-.2-.7-.6 0-.6.6 0 1 .6 1.2.8.7 1.2 1.9 1 2.4.7 0-.5.2-.9.5-1-1.8-.3-3.7-1-3.7-4 0-.9.3-1.6.8-2.2 0-.2-.3-1 .1-2 0 0 .7-.3 2.2.7a7.4 7.4 0 0 1 4 0c1.5-1 2.2-.8 2.2-.8.5 1.1.2 2 .1 2.1.5.6.8 1.3.8 2.2 0 3-1.9 3.7-3.6 4 .3.2.5.7.5 1.4v2.2c0 .2.1.5.5.4A8 8 0 0 0 16 8a8 8 0 0 0-8-8z"/></svg></span>Edit on GitHub</a></li>
          </ul>
        </div>
        <hr>
      </header>

      <div id="toc">
        <h2>Table of Contents</h2>
        <ul>
<li>
<p><span class="stability_1"><a href="#esm_ecmascript_modules">ECMAScript modules</a></span></p>
<ul>
<li><a href="#esm_introduction">Introduction</a></li>
<li>
<p><a href="#esm_enabling">Enabling</a></p>
<ul>
<li><a href="#esm_package_json_type_field"><code>package.json</code> <code>"type"</code> field</a></li>
<li><a href="#esm_package_scope_and_file_extensions">Package scope and file extensions</a></li>
<li><a href="#esm_input_type_flag"><code>--input-type</code> flag</a></li>
</ul>
</li>
<li>
<p><a href="#esm_packages">Packages</a></p>
<ul>
<li>
<p><a href="#esm_package_entry_points">Package entry points</a></p>
<ul>
<li><a href="#esm_main_entry_point_export">Main entry point export</a></li>
<li><a href="#esm_subpath_exports">Subpath exports</a></li>
<li><a href="#esm_package_exports_fallbacks">Package exports fallbacks</a></li>
<li><a href="#esm_exports_sugar">Exports sugar</a></li>
<li><a href="#esm_conditional_exports">Conditional exports</a></li>
<li><a href="#esm_nested_conditions">Nested conditions</a></li>
<li><a href="#esm_self_referencing_a_package_using_its_name">Self-referencing a package using its name</a></li>
</ul>
</li>
<li>
<p><a href="#esm_dual_commonjs_es_module_packages">Dual CommonJS/ES module packages</a></p>
<ul>
<li><a href="#esm_dual_package_hazard">Dual package hazard</a></li>
<li>
<p><a href="#esm_writing_dual_packages_while_avoiding_or_minimizing_hazards">Writing dual packages while avoiding or minimizing hazards</a></p>
<ul>
<li><a href="#esm_approach_1_use_an_es_module_wrapper">Approach #1: Use an ES module wrapper</a></li>
<li><a href="#esm_approach_2_isolate_state">Approach #2: Isolate state</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#esm_import_specifiers"><code>import</code> Specifiers</a></p>
<ul>
<li>
<p><a href="#esm_terminology">Terminology</a></p>
<ul>
<li><a href="#esm_data_imports"><code>data:</code> Imports</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#esm_import_meta"><code>import.meta</code></a></li>
<li>
<p><a href="#esm_differences_between_es_modules_and_commonjs">Differences between ES modules and CommonJS</a></p>
<ul>
<li><a href="#esm_mandatory_file_extensions">Mandatory file extensions</a></li>
<li><a href="#esm_no_node_path">No <code>NODE_PATH</code></a></li>
<li><a href="#esm_no_require_exports_module_exports_filename_dirname">No <code>require</code>, <code>exports</code>, <code>module.exports</code>, <code>__filename</code>, <code>__dirname</code></a></li>
<li><a href="#esm_no_require_resolve">No <code>require.resolve</code></a></li>
<li><a href="#esm_no_require_extensions">No <code>require.extensions</code></a></li>
<li><a href="#esm_no_require_cache">No <code>require.cache</code></a></li>
<li><a href="#esm_url_based_paths">URL-based paths</a></li>
</ul>
</li>
<li>
<p><a href="#esm_interoperability_with_commonjs">Interoperability with CommonJS</a></p>
<ul>
<li><a href="#esm_require"><code>require</code></a></li>
<li><a href="#esm_import_statements"><code>import</code> statements</a></li>
<li><a href="#esm_import_expressions"><code>import()</code> expressions</a></li>
</ul>
</li>
<li><a href="#esm_commonjs_json_and_native_modules">CommonJS, JSON, and native modules</a></li>
<li><a href="#esm_builtin_modules">Builtin modules</a></li>
<li><a href="#esm_experimental_json_modules">Experimental JSON modules</a></li>
<li><a href="#esm_experimental_wasm_modules">Experimental Wasm modules</a></li>
<li>
<p><a href="#esm_experimental_loaders">Experimental loaders</a></p>
<ul>
<li>
<p><a href="#esm_hooks">Hooks</a></p>
<ul>
<li><a href="#esm_code_resolve_code_hook"><code>resolve</code> hook</a></li>
<li><a href="#esm_code_getformat_code_hook"><code>getFormat</code> hook</a></li>
<li><a href="#esm_code_getsource_code_hook"><code>getSource</code> hook</a></li>
<li><a href="#esm_code_transformsource_code_hook"><code>transformSource</code> hook</a></li>
<li><a href="#esm_code_getglobalpreloadcode_code_hook"><code>getGlobalPreloadCode</code> hook</a></li>
<li><a href="#esm_code_dynamicinstantiate_code_hook"><code>dynamicInstantiate</code> hook</a></li>
</ul>
</li>
<li>
<p><a href="#esm_examples">Examples</a></p>
<ul>
<li><a href="#esm_https_loader">HTTPS loader</a></li>
<li><a href="#esm_transpiler_loader">Transpiler loader</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#esm_resolution_algorithm">Resolution algorithm</a></p>
<ul>
<li><a href="#esm_features">Features</a></li>
<li><a href="#esm_resolver_algorithm">Resolver algorithm</a></li>
<li><a href="#esm_customizing_esm_specifier_resolution_algorithm">Customizing ESM specifier resolution algorithm</a></li>
</ul>
</li>
</ul>
</li>
</ul>
      </div>

      <div id="apicontent">
        <h1>ECMAScript modules<span><a class="mark" href="#esm_ecmascript_modules" id="esm_ecmascript_modules">#</a></span></h1>


<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<h2>Introduction<span><a class="mark" href="#esm_introduction" id="esm_introduction">#</a></span></h2>

<p>ECMAScript modules are <a href="https://tc39.github.io/ecma262/#sec-modules">the official standard format</a> to package JavaScript
code 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
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export"><code>export</code></a> statements.</p>
<p>The following example of an ES module exports a function:</p>
<pre><code class="language-js">// addTwo.mjs
function addTwo(num) {
  return num + 2;
}

export { addTwo };
</code></pre>
<p>The following example of an ES module imports the function from <code>addTwo.mjs</code>:</p>
<pre><code class="language-js">// app.mjs
import { addTwo } from './addTwo.mjs';

// Prints: 6
console.log(addTwo(4));
</code></pre>
<p>Node.js fully supports ECMAScript modules as they are currently specified and
provides limited interoperability between them and the existing module format,
<a href="modules.html">CommonJS</a>.</p>
<p>Node.js contains support for ES Modules based upon the
<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>
<p>Expect major changes in the implementation including interoperability support,
specifier resolution, and default behavior.</p>
<h2>Enabling<span><a class="mark" href="#esm_enabling" id="esm_enabling">#</a></span></h2>

<p>Experimental support for ECMAScript modules is enabled by default.
Node.js will treat the following as ES modules when passed to <code>node</code> as the
initial input, or when referenced by <code>import</code> statements within ES module code:</p>
<ul>
<li>
<p>Files ending in <code>.mjs</code>.</p>
</li>
<li>
<p>Files ending in <code>.js</code> when the nearest parent <code>package.json</code> file contains a
top-level field <code>"type"</code> with a value of <code>"module"</code>.</p>
</li>
<li>
<p>Strings passed in as an argument to <code>--eval</code> or <code>--print</code>, or piped to
<code>node</code> via <code>STDIN</code>, with the flag <code>--input-type=module</code>.</p>
</li>
</ul>
<p>Node.js will treat as CommonJS all other forms of input, such as <code>.js</code> files
where the nearest parent <code>package.json</code> file contains no top-level <code>"type"</code>
field, or string input without the flag <code>--input-type</code>. This behavior is to
preserve backward compatibility. However, now that Node.js supports both
CommonJS and ES modules, it is best to be explicit whenever possible. Node.js
will treat the following as CommonJS when passed to <code>node</code> as the initial input,
or when referenced by <code>import</code> statements within ES module code:</p>
<ul>
<li>
<p>Files ending in <code>.cjs</code>.</p>
</li>
<li>
<p>Files ending in <code>.js</code> when the nearest parent <code>package.json</code> file contains a
top-level field <code>"type"</code> with a value of <code>"commonjs"</code>.</p>
</li>
<li>
<p>Strings passed in as an argument to <code>--eval</code> or <code>--print</code>, or piped to
<code>node</code> via <code>STDIN</code>, with the flag <code>--input-type=commonjs</code>.</p>
</li>
</ul>
<h3><code>package.json</code> <code>"type"</code> field<span><a class="mark" href="#esm_package_json_type_field" id="esm_package_json_type_field">#</a></span></h3>
<p>Files ending with <code>.js</code> will be loaded as ES modules when the nearest parent
<code>package.json</code> file contains a top-level field <code>"type"</code> with a value of
<code>"module"</code>.</p>
<p>The nearest parent <code>package.json</code> is defined as the first <code>package.json</code> found
when searching in the current folder, that folder’s parent, and so on up
until the root of the volume is reached.</p>
<!-- eslint-skip -->
<pre><code class="language-js">// package.json
{
  "type": "module"
}
</code></pre>
<pre><code class="language-bash"># In same folder as above package.json
node my-app.js # Runs as ES module
</code></pre>
<p>If the nearest parent <code>package.json</code> lacks a <code>"type"</code> field, or contains
<code>"type": "commonjs"</code>, <code>.js</code> files are treated as CommonJS. If the volume root is
reached and no <code>package.json</code> is found, Node.js defers to the default, a
<code>package.json</code> with no <code>"type"</code> field.</p>
<p><code>import</code> statements of <code>.js</code> files are treated as ES modules if the nearest
parent <code>package.json</code> contains <code>"type": "module"</code>.</p>
<pre><code class="language-js">// my-app.js, part of the same example as above
import './startup.js'; // Loaded as ES module because of package.json
</code></pre>
<p>Package authors should include the <code>"type"</code> field, even in packages where all
sources are CommonJS. Being explicit about the <code>type</code> of the package will
future-proof the package in case the default type of Node.js ever changes, and
it will also make things easier for build tools and loaders to determine how the
files in the package should be interpreted.</p>
<p>Regardless of the value of the <code>"type"</code> field, <code>.mjs</code> files are always treated
as ES modules and <code>.cjs</code> files are always treated as CommonJS.</p>
<h3>Package scope and file extensions<span><a class="mark" href="#esm_package_scope_and_file_extensions" id="esm_package_scope_and_file_extensions">#</a></span></h3>
<p>A folder containing a <code>package.json</code> file, and all subfolders below that folder
down until the next folder containing another <code>package.json</code>, is considered a
<em>package scope</em>. The <code>"type"</code> field defines how <code>.js</code> files should be treated
within a particular <code>package.json</code> file’s package scope. Every package in a
project’s <code>node_modules</code> folder contains its own <code>package.json</code> file, so each
project’s dependencies have their own package scopes. A <code>package.json</code> lacking a
<code>"type"</code> field is treated as if it contained <code>"type": "commonjs"</code>.</p>
<p>The package scope applies not only to initial entry points (<code>node my-app.js</code>)
but also to files referenced by <code>import</code> statements and <code>import()</code> expressions.</p>
<pre><code class="language-js">// my-app.js, in an ES module package scope because there is a package.json
// file in the same folder with "type": "module".

import './startup/init.js';
// Loaded as ES module since ./startup contains no package.json file,
// and therefore inherits the ES module package scope from one level up.

import 'commonjs-package';
// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
// lacks a "type" field or contains "type": "commonjs".

import './node_modules/commonjs-package/index.js';
// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
// lacks a "type" field or contains "type": "commonjs".
</code></pre>
<p>Files ending with <code>.mjs</code> are always loaded as ES modules regardless of package
scope.</p>
<p>Files ending with <code>.cjs</code> are always loaded as CommonJS regardless of package
scope.</p>
<pre><code class="language-js">import './legacy-file.cjs';
// Loaded as CommonJS since .cjs is always loaded as CommonJS.

import 'commonjs-package/src/index.mjs';
// Loaded as ES module since .mjs is always loaded as ES module.
</code></pre>
<p>The <code>.mjs</code> and <code>.cjs</code> extensions may be used to mix types within the same
package scope:</p>
<ul>
<li>
<p>Within a <code>"type": "module"</code> package scope, Node.js can be instructed to
interpret a particular file as CommonJS by naming it with a <code>.cjs</code> extension
(since both <code>.js</code> and <code>.mjs</code> files are treated as ES modules within a
<code>"module"</code> package scope).</p>
</li>
<li>
<p>Within a <code>"type": "commonjs"</code> package scope, Node.js can be instructed to
interpret a particular file as an ES module by naming it with an <code>.mjs</code>
extension (since both <code>.js</code> and <code>.cjs</code> files are treated as CommonJS within a
<code>"commonjs"</code> package scope).</p>
</li>
</ul>
<h3><code>--input-type</code> flag<span><a class="mark" href="#esm_input_type_flag" id="esm_input_type_flag">#</a></span></h3>
<p>Strings passed in as an argument to <code>--eval</code> or <code>--print</code> (or <code>-e</code> or <code>-p</code>), or
piped to <code>node</code> via <code>STDIN</code>, will be treated as ES modules when the
<code>--input-type=module</code> flag is set.</p>
<pre><code class="language-bash">node --input-type=module --eval "import { sep } from 'path'; console.log(sep);"

echo "import { sep } from 'path'; console.log(sep);" | node --input-type=module
</code></pre>
<p>For completeness there is also <code>--input-type=commonjs</code>, for explicitly running
string input as CommonJS. This is the default behavior if <code>--input-type</code> is
unspecified.</p>
<h2>Packages<span><a class="mark" href="#esm_packages" id="esm_packages">#</a></span></h2>
<h3>Package entry points<span><a class="mark" href="#esm_package_entry_points" id="esm_package_entry_points">#</a></span></h3>
<p>In a package’s <code>package.json</code> file, two fields can define entry points for a
package: <code>"main"</code> and <code>"exports"</code>. The <code>"main"</code> field is supported in all
versions of Node.js, but its capabilities are limited: it only defines the main
entry point of the package.</p>
<p>The <code>"exports"</code> field provides an alternative to <code>"main"</code> where the package
main entry point can be defined while also encapsulating the package,
<strong>preventing any other entry points besides those defined in <code>"exports"</code></strong>.
This encapsulation allows module authors to define a public interface for
their package.</p>
<p>If both <code>"exports"</code> and <code>"main"</code> are defined, the <code>"exports"</code> field takes
precedence over <code>"main"</code>. <code>"exports"</code> are not specific to ES modules or
CommonJS; <code>"main"</code> will be overridden by <code>"exports"</code> if it exists. As such
<code>"main"</code> cannot be used as a fallback for CommonJS but it can be used as a
fallback for legacy versions of Node.js that do not support the <code>"exports"</code>
field.</p>
<p><a href="#esm_conditional_exports">Conditional exports</a> can be used within <code>"exports"</code> to define different
package entry points per environment, including whether the package is
referenced via <code>require</code> or via <code>import</code>. For more information about supporting
both CommonJS and ES Modules in a single package please consult
<a href="#esm_dual_commonjs_es_module_packages">the dual CommonJS/ES module packages section</a>.</p>
<p><strong>Warning</strong>: Introducing the <code>"exports"</code> field prevents consumers of a package
from using any entry points that are not defined, including the <code>package.json</code>
(e.g. <code>require('your-package/package.json')</code>. <strong>This will likely be a breaking
change.</strong></p>
<p>To make the introduction of <code>"exports"</code> non-breaking, ensure that every
previously supported entry point is exported. It is best to explicitly specify
entry points so that the package’s public API is well-defined. For example,
a project that previous exported <code>main</code>, <code>lib</code>,
<code>feature</code>, and the <code>package.json</code> could use the following <code>package.exports</code>:</p>
<pre><code class="language-json">{
  "name": "my-mod",
  "exports": {
    ".": "./lib/index.js",
    "./lib": "./lib/index.js",
    "./lib/index": "./lib/index.js",
    "./lib/index.js": "./lib/index.js",
    "./feature": "./feature/index.js",
    "./feature/index.js": "./feature/index.js",
    "./package.json": "./package.json"
  }
}
</code></pre>
<p>Alternatively a project could choose to export entire folders:</p>
<pre><code class="language-json">{
  "name": "my-mod",
  "exports": {
    ".": "./lib/index.js",
    "./lib": "./lib/index.js",
    "./lib/": "./lib/",
    "./feature": "./feature/index.js",
    "./feature/": "./feature/",
    "./package.json": "./package.json"
  }
}
</code></pre>
<p>As a last resort, package encapsulation can be disabled entirely by creating an
export for the root of the package <code>"./": "./"</code>. This will expose every file in
the package at the cost of disabling the encapsulation and potential tooling
benefits this provides. As the ES Module loader in Node.js enforces the use of
<a href="#esm_mandatory_file_extensions">the full specifier path</a>, exporting the root rather than being explicit
about entry is less expressive than either of the prior examples. Not only
will encapsulation be lost but module consumers will be unable to
<code>import feature from 'my-mod/feature'</code> as they will need to provide the full
path <code>import feature from 'my-mod/feature/index.js</code>.</p>
<h4>Main entry point export<span><a class="mark" href="#esm_main_entry_point_export" id="esm_main_entry_point_export">#</a></span></h4>
<p>To set the main entry point for a package, it is advisable to define both
<code>"exports"</code> and <code>"main"</code> in the package’s <code>package.json</code> file:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "main": "./main.js",
  "exports": "./main.js"
}
</code></pre>
<p>The benefit of doing this is that when using the <code>"exports"</code> field all
subpaths of the package will no longer be available to importers under
<code>require('pkg/subpath.js')</code>, and instead they will get a new error,
<code>ERR_PACKAGE_PATH_NOT_EXPORTED</code>.</p>
<p>This encapsulation of exports provides more reliable guarantees
about package interfaces for tools and when handling semver upgrades for a
package. It is not a strong encapsulation since a direct require of any
absolute subpath of the package such as
<code>require('/path/to/node_modules/pkg/subpath.js')</code> will still load <code>subpath.js</code>.</p>
<h4>Subpath exports<span><a class="mark" href="#esm_subpath_exports" id="esm_subpath_exports">#</a></span></h4>
<p>When using the <code>"exports"</code> field, custom subpaths can be defined along
with the main entry point by treating the main entry point as the
<code>"."</code> subpath:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "main": "./main.js",
  "exports": {
    ".": "./main.js",
    "./submodule": "./src/submodule.js"
  }
}
</code></pre>
<p>Now only the defined subpath in <code>"exports"</code> can be imported by a
consumer:</p>
<pre><code class="language-js">import submodule from 'es-module-package/submodule';
// Loads ./node_modules/es-module-package/src/submodule.js
</code></pre>
<p>While other subpaths will error:</p>
<pre><code class="language-js">import submodule from 'es-module-package/private-module.js';
// Throws ERR_PACKAGE_PATH_NOT_EXPORTED
</code></pre>
<p>Entire folders can also be mapped with package exports:</p>
<!-- eslint-skip -->
<pre><code class="language-js">// ./node_modules/es-module-package/package.json
{
  "exports": {
    "./features/": "./src/features/"
  }
}
</code></pre>
<p>With the above, all modules within the <code>./src/features/</code> folder
are exposed deeply to <code>import</code> and <code>require</code>:</p>
<pre><code class="language-js">import feature from 'es-module-package/features/x.js';
// Loads ./node_modules/es-module-package/src/features/x.js
</code></pre>
<p>When using folder mappings, ensure that you do want to expose every
module inside the subfolder. Any modules which are not public
should be moved to another folder to retain the encapsulation
benefits of exports.</p>
<h4>Package exports fallbacks<span><a class="mark" href="#esm_package_exports_fallbacks" id="esm_package_exports_fallbacks">#</a></span></h4>
<p>For possible new specifier support in future, array fallbacks are
supported for all invalid specifiers:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "exports": {
    "./submodule": ["not:valid", "./submodule.js"]
  }
}
</code></pre>
<p>Since <code>"not:valid"</code> is not a valid specifier, <code>"./submodule.js"</code> is used
instead as the fallback, as if it were the only target.</p>
<h4>Exports sugar<span><a class="mark" href="#esm_exports_sugar" id="esm_exports_sugar">#</a></span></h4>
<p>If the <code>"."</code> export is the only export, the <code>"exports"</code> field provides sugar
for this case being the direct <code>"exports"</code> field value.</p>
<p>If the <code>"."</code> export has a fallback array or string value, then the <code>"exports"</code>
field can be set to this value directly.</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "exports": {
    ".": "./main.js"
  }
}
</code></pre>
<p>can be written:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "exports": "./main.js"
}
</code></pre>
<h4>Conditional exports<span><a class="mark" href="#esm_conditional_exports" id="esm_conditional_exports">#</a></span></h4>
<p>Conditional exports provide a way to map to different paths depending on
certain conditions. They are supported for both CommonJS and ES module imports.</p>
<p>For example, a package that wants to provide different ES module exports for
<code>require()</code> and <code>import</code> can be written:</p>
<!-- eslint-skip -->
<pre><code class="language-js">// package.json
{
  "main": "./main-require.cjs",
  "exports": {
    "import": "./main-module.js",
    "require": "./main-require.cjs"
  },
  "type": "module"
}
</code></pre>
<p>Node.js supports the following conditions:</p>
<ul>
<li><code>"import"</code> - matched when the package is loaded via <code>import</code> or
<code>import()</code>. Can reference either an ES module or CommonJS file, as both
<code>import</code> and <code>import()</code> can load either ES module or CommonJS sources.</li>
<li><code>"require"</code> - matched when the package is loaded via <code>require()</code>.
As <code>require()</code> only supports CommonJS, the referenced file must be CommonJS.</li>
<li><code>"node"</code> - matched for any Node.js environment. Can be a CommonJS or ES
module file. <em>This condition should always come after <code>"import"</code> or
<code>"require"</code>.</em></li>
<li><code>"default"</code> - the generic fallback that will always match. Can be a CommonJS
or ES module file. <em>This condition should always come last.</em></li>
</ul>
<p>Condition matching is applied in object order from first to last within the
<code>"exports"</code> object. <em>The general rule is that conditions should be used
from most specific to least specific in object order.</em></p>
<p>Other conditions such as <code>"browser"</code>, <code>"electron"</code>, <code>"deno"</code>, <code>"react-native"</code>,
etc. are ignored by Node.js but may be used by other runtimes or tools.
Further restrictions, definitions or guidance on condition names may be
provided in the future.</p>
<p>Using the <code>"import"</code> and <code>"require"</code> conditions can lead to some hazards,
which are explained further in
<a href="#esm_dual_commonjs_es_module_packages">the dual CommonJS/ES module packages section</a>.</p>
<p>Conditional exports can also be extended to exports subpaths, for example:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "main": "./main.js",
  "exports": {
    ".": "./main.js",
    "./feature": {
      "browser": "./feature-browser.js",
      "default": "./feature.js"
    }
  }
}
</code></pre>
<p>Defines a package where <code>require('pkg/feature')</code> and <code>import 'pkg/feature'</code>
could provide different implementations between the browser and Node.js,
given third-party tool support for a <code>"browser"</code> condition.</p>
<h4>Nested conditions<span><a class="mark" href="#esm_nested_conditions" id="esm_nested_conditions">#</a></span></h4>
<p>In addition to direct mappings, Node.js also supports nested condition objects.</p>
<p>For example, to define a package that only has dual mode entry points for
use in Node.js but not the browser:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "main": "./main.js",
  "exports": {
    "browser": "./feature-browser.mjs",
    "node": {
      "import": "./feature-node.mjs",
      "require": "./feature-node.cjs"
    }
  }
}
</code></pre>
<p>Conditions continue to be matched in order as with flat conditions. If
a nested conditional does not have any mapping it will continue checking
the remaining conditions of the parent condition. In this way nested
conditions behave analogously to nested JavaScript <code>if</code> statements.</p>
<h4>Self-referencing a package using its name<span><a class="mark" href="#esm_self_referencing_a_package_using_its_name" id="esm_self_referencing_a_package_using_its_name">#</a></span></h4>
<p>Within a package, the values defined in the package’s
<code>package.json</code> <code>"exports"</code> field can be referenced via the package’s name.
For example, assuming the <code>package.json</code> is:</p>
<pre><code class="language-json">// package.json
{
  "name": "a-package",
  "exports": {
    ".": "./main.mjs",
    "./foo": "./foo.js"
  }
}
</code></pre>
<p>Then any module <em>in that package</em> can reference an export in the package itself:</p>
<pre><code class="language-js">// ./a-module.mjs
import { something } from 'a-package'; // Imports "something" from ./main.mjs.
</code></pre>
<p>Self-referencing is available only if <code>package.json</code> has <code>exports</code>, and will
allow importing only what that <code>exports</code> (in the <code>package.json</code>) allows.
So the code below, given the package above, will generate a runtime error:</p>
<pre><code class="language-js">// ./another-module.mjs

// Imports "another" from ./m.mjs. Fails because
// the "package.json" "exports" field
// does not provide an export named "./m.mjs".
import { another } from 'a-package/m.mjs';
</code></pre>
<p>Self-referencing is also available when using <code>require</code>, both in an ES module,
and in a CommonJS one. For example, this code will also work:</p>
<pre><code class="language-js">// ./a-module.js
const { something } = require('a-package/foo'); // Loads from ./foo.js.
</code></pre>
<h3>Dual CommonJS/ES module packages<span><a class="mark" href="#esm_dual_commonjs_es_module_packages" id="esm_dual_commonjs_es_module_packages">#</a></span></h3>
<p>Prior to the introduction of support for ES modules in Node.js, it was a common
pattern for package authors to include both CommonJS and ES module JavaScript
sources in their package, with <code>package.json</code> <code>"main"</code> specifying the CommonJS
entry point and <code>package.json</code> <code>"module"</code> specifying the ES module entry point.
This enabled Node.js to run the CommonJS entry point while build tools such as
bundlers used the ES module entry point, since Node.js ignored (and still
ignores) the top-level <code>"module"</code> field.</p>
<p>Node.js can now run ES module entry points, and a package can contain both
CommonJS and ES module entry points (either via separate specifiers such as
<code>'pkg'</code> and <code>'pkg/es-module'</code>, or both at the same specifier via <a href="#esm_conditional_exports">Conditional
exports</a>). Unlike in the scenario where <code>"module"</code> is only used by bundlers,
or ES module files are transpiled into CommonJS on the fly before evaluation by
Node.js, the files referenced by the ES module entry point are evaluated as ES
modules.</p>
<h4>Dual package hazard<span><a class="mark" href="#esm_dual_package_hazard" id="esm_dual_package_hazard">#</a></span></h4>
<p>When an application is using a package that provides both CommonJS and ES module
sources, there is a risk of certain bugs if both versions of the package get
loaded. This potential comes from the fact that the <code>pkgInstance</code> created by
<code>const pkgInstance = require('pkg')</code> is not the same as the <code>pkgInstance</code>
created by <code>import pkgInstance from 'pkg'</code> (or an alternative main path like
<code>'pkg/module'</code>). This is the “dual package hazard,” where two versions of the
same package can be loaded within the same runtime environment. While it is
unlikely that an application or package would intentionally load both versions
directly, it is common for an application to load one version while a dependency
of the application loads the other version. This hazard can happen because
Node.js supports intermixing CommonJS and ES modules, and can lead to unexpected
behavior.</p>
<p>If the package main export is a constructor, an <code>instanceof</code> comparison of
instances created by the two versions returns <code>false</code>, and if the export is an
object, properties added to one (like <code>pkgInstance.foo = 3</code>) are not present on
the other. This differs from how <code>import</code> and <code>require</code> statements work in
all-CommonJS or all-ES module environments, respectively, and therefore is
surprising to users. It also differs from the behavior users are familiar with
when 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>
<h4>Writing dual packages while avoiding or minimizing hazards<span><a class="mark" href="#esm_writing_dual_packages_while_avoiding_or_minimizing_hazards" id="esm_writing_dual_packages_while_avoiding_or_minimizing_hazards">#</a></span></h4>
<p>First, the hazard described in the previous section occurs when a package
contains both CommonJS and ES module sources and both sources are provided for
use in Node.js, either via separate main entry points or exported paths. A
package could instead be written where any version of Node.js receives only
CommonJS sources, and any separate ES module sources the package may contain
could be intended only for other environments such as browsers. Such a package
would be usable by any version of Node.js, since <code>import</code> can refer to CommonJS
files; but it would not provide any of the advantages of using ES module syntax.</p>
<p>A package could also switch from CommonJS to ES module syntax in a breaking
change version bump. This has the disadvantage that the newest version
of the package would only be usable in ES module-supporting versions of Node.js.</p>
<p>Every pattern has tradeoffs, but there are two broad approaches that satisfy the
following conditions:</p>
<ol>
<li>The package is usable via both <code>require</code> and <code>import</code>.</li>
<li>The package is usable in both current Node.js and older versions of Node.js
that lack support for ES modules.</li>
<li>The package main entry point, e.g. <code>'pkg'</code> can be used by both <code>require</code> to
resolve to a CommonJS file and by <code>import</code> to resolve to an ES module file.
(And likewise for exported paths, e.g. <code>'pkg/feature'</code>.)</li>
<li>The package provides named exports, e.g. <code>import { name } from 'pkg'</code> rather
than <code>import pkg from 'pkg'; pkg.name</code>.</li>
<li>The package is potentially usable in other ES module environments such as
browsers.</li>
<li>The hazards described in the previous section are avoided or minimized.</li>
</ol>
<h5>Approach #1: Use an ES module wrapper<span><a class="mark" href="#esm_approach_1_use_an_es_module_wrapper" id="esm_approach_1_use_an_es_module_wrapper">#</a></span></h5>
<p>Write the package in CommonJS or transpile ES module sources into CommonJS, and
create an ES module wrapper file that defines the named exports. Using
<a href="#esm_conditional_exports">Conditional exports</a>, the ES module wrapper is used for <code>import</code> and the
CommonJS entry point for <code>require</code>.</p>
<!-- eslint-skip -->
<pre><code class="language-js">// ./node_modules/pkg/package.json
{
  "type": "module",
  "main": "./index.cjs",
  "exports": {
    "import": "./wrapper.mjs",
    "require": "./index.cjs"
  }
}
</code></pre>
<pre><code class="language-js">// ./node_modules/pkg/index.cjs
exports.name = 'value';
</code></pre>
<pre><code class="language-js">// ./node_modules/pkg/wrapper.mjs
import cjsModule from './index.cjs';
export const name = cjsModule.name;
</code></pre>
<p>In this example, the <code>name</code> from <code>import { name } from 'pkg'</code> is the same
singleton as the <code>name</code> from <code>const { name } = require('pkg')</code>. Therefore <code>===</code>
returns <code>true</code> when comparing the two <code>name</code>s and the divergent specifier hazard
is avoided.</p>
<p>If the module is not simply a list of named exports, but rather contains a
unique function or object export like <code>module.exports = function () { ... }</code>,
or if support in the wrapper for the <code>import pkg from 'pkg'</code> pattern is desired,
then the wrapper would instead be written to export the default optionally
along with any named exports as well:</p>
<pre><code class="language-js">import cjsModule from './index.cjs';
export const name = cjsModule.name;
export default cjsModule;
</code></pre>
<p>This approach is appropriate for any of the following use cases:</p>
<ul>
<li>The package is currently written in CommonJS and the author would prefer not
to refactor it into ES module syntax, but wishes to provide named exports for
ES module consumers.</li>
<li>The package has other packages that depend on it, and the end user might
install both this package and those other packages. For example a <code>utilities</code>
package is used directly in an application, and a <code>utilities-plus</code> package
adds a few more functions to <code>utilities</code>. Because the wrapper exports
underlying CommonJS files, it doesn’t matter if <code>utilities-plus</code> is written in
CommonJS or ES module syntax; it will work either way.</li>
<li>The package stores internal state, and the package author would prefer not to
refactor the package to isolate its state management. See the next section.</li>
</ul>
<p>A variant of this approach not requiring conditional exports for consumers could
be to add an export, e.g. <code>"./module"</code>, to point to an all-ES module-syntax
version of the package. This could be used via <code>import 'pkg/module'</code> by users
who are certain that the CommonJS version will not be loaded anywhere in the
application, such as by dependencies; or if the CommonJS version can be loaded
but doesn’t affect the ES module version (for example, because the package is
stateless):</p>
<!-- eslint-skip -->
<pre><code class="language-js">// ./node_modules/pkg/package.json
{
  "type": "module",
  "main": "./index.cjs",
  "exports": {
    ".": "./index.cjs",
    "./module": "./wrapper.mjs"
  }
}
</code></pre>
<h5>Approach #2: Isolate state<span><a class="mark" href="#esm_approach_2_isolate_state" id="esm_approach_2_isolate_state">#</a></span></h5>
<p>A <code>package.json</code> file can define the separate CommonJS and ES module entry
points directly:</p>
<!-- eslint-skip -->
<pre><code class="language-js">// ./node_modules/pkg/package.json
{
  "type": "module",
  "main": "./index.cjs",
  "exports": {
    "import": "./index.mjs",
    "require": "./index.cjs"
  }
}
</code></pre>
<p>This can be done if both the CommonJS and ES module versions of the package are
equivalent, for example because one is the transpiled output of the other; and
the package’s management of state is carefully isolated (or the package is
stateless).</p>
<p>The reason that state is an issue is because both the CommonJS and ES module
versions of the package may get used within an application; for example, the
user’s application code could <code>import</code> the ES module version while a dependency
<code>require</code>s the CommonJS version. If that were to occur, two copies of the
package would be loaded in memory and therefore two separate states would be
present. This would likely cause hard-to-troubleshoot bugs.</p>
<p>Aside from writing a stateless package (if JavaScript’s <code>Math</code> were a package,
for example, it would be stateless as all of its methods are static), there are
some ways to isolate state so that it’s shared between the potentially loaded
CommonJS and ES module instances of the package:</p>
<ol>
<li>
<p>If possible, contain all state within an instantiated object. JavaScript’s
<code>Date</code>, for example, needs to be instantiated to contain state; if it were a
package, it would be used like this:</p>
<pre><code class="language-js">import Date from 'date';
const someDate = new Date();
// someDate contains state; Date does not
</code></pre>
<p>The <code>new</code> keyword isn’t required; a package’s function can return a new
object, or modify a passed-in object, to keep the state external to the
package.</p>
</li>
<li>
<p>Isolate the state in one or more CommonJS files that are shared between the
CommonJS and ES module versions of the package. For example, if the CommonJS
and ES module entry points are <code>index.cjs</code> and <code>index.mjs</code>, respectively:</p>
<pre><code class="language-js">// ./node_modules/pkg/index.cjs
const state = require('./state.cjs');
module.exports.state = state;
</code></pre>
<pre><code class="language-js">// ./node_modules/pkg/index.mjs
import state from './state.cjs';
export {
  state
};
</code></pre>
<p>Even if <code>pkg</code> is used via both <code>require</code> and <code>import</code> in an application (for
example, via <code>import</code> in application code and via <code>require</code> by a dependency)
each reference of <code>pkg</code> will contain the same state; and modifying that
state from either module system will apply to both.</p>
</li>
</ol>
<p>Any plugins that attach to the package’s singleton would need to separately
attach to both the CommonJS and ES module singletons.</p>
<p>This approach is appropriate for any of the following use cases:</p>
<ul>
<li>The package is currently written in ES module syntax and the package author
wants that version to be used wherever such syntax is supported.</li>
<li>The package is stateless or its state can be isolated without too much
difficulty.</li>
<li>The package is unlikely to have other public packages that depend on it, or if
it does, the package is stateless or has state that need not be shared between
dependencies or with the overall application.</li>
</ul>
<p>Even with isolated state, there is still the cost of possible extra code
execution between the CommonJS and ES module versions of a package.</p>
<p>As with the previous approach, a variant of this approach not requiring
conditional exports for consumers could be to add an export, e.g.
<code>"./module"</code>, to point to an all-ES module-syntax version of the package:</p>
<!-- eslint-skip -->
<pre><code class="language-js">// ./node_modules/pkg/package.json
{
  "type": "module",
  "main": "./index.cjs",
  "exports": {
    ".": "./index.cjs",
    "./module": "./index.mjs"
  }
}
</code></pre>
<h2><code>import</code> Specifiers<span><a class="mark" href="#esm_import_specifiers" id="esm_import_specifiers">#</a></span></h2>
<h3>Terminology<span><a class="mark" href="#esm_terminology" id="esm_terminology">#</a></span></h3>
<p>The <em>specifier</em> of an <code>import</code> statement is the string after the <code>from</code> keyword,
e.g. <code>'path'</code> in <code>import { sep } from 'path'</code>. Specifiers are also used in
<code>export from</code> statements, and as the argument to an <code>import()</code> expression.</p>
<p>There are four types of specifiers:</p>
<ul>
<li>
<p><em>Bare specifiers</em> like <code>'some-package'</code>. They refer to an entry point of a
package by the package name.</p>
</li>
<li>
<p><em>Deep import specifiers</em> like <code>'some-package/lib/shuffle.mjs'</code>. They refer to
a path within a package prefixed by the package name.</p>
</li>
<li>
<p><em>Relative specifiers</em> like <code>'./startup.js'</code> or <code>'../config.mjs'</code>. They refer
to a path relative to the location of the importing file.</p>
</li>
<li>
<p><em>Absolute specifiers</em> like <code>'file:///opt/nodejs/config.js'</code>. They refer
directly and explicitly to a full path.</p>
</li>
</ul>
<p>Bare specifiers, and the bare specifier portion of deep import specifiers, are
strings; but everything else in a specifier is a URL.</p>
<p>Only <code>file:</code> and <code>data:</code> URLs are supported. A specifier like
<code>'https://example.com/app.js'</code> may be supported by browsers but it is not
supported in Node.js.</p>
<p>Specifiers may not begin with <code>/</code> or <code>//</code>. These are reserved for potential
future use. The root of the current volume may be referenced via <code>file:///</code>.</p>
<h4><code>data:</code> Imports<span><a class="mark" href="#esm_data_imports" id="esm_data_imports">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<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>
<ul>
<li><code>text/javascript</code> for ES Modules</li>
<li><code>application/json</code> for JSON</li>
<li><code>application/wasm</code> for WASM.</li>
</ul>
<p><code>data:</code> URLs only resolve <a href="#esm_terminology"><em>Bare specifiers</em></a> for builtin modules
and <a href="#esm_terminology"><em>Absolute specifiers</em></a>. Resolving
<a href="#esm_terminology"><em>Relative specifiers</em></a> will not work because <code>data:</code> is not a
<a href="https://url.spec.whatwg.org/#special-scheme">special scheme</a>. For example, attempting to load <code>./foo</code>
from <code>data:text/javascript,import "./foo";</code> will fail to resolve since there
is no concept of relative resolution for <code>data:</code> URLs. An example of a <code>data:</code>
URLs being used is:</p>
<pre><code class="language-js">import 'data:text/javascript,console.log("hello!");';
import _ from 'data:application/json,"world!"';
</code></pre>
<h2><code>import.meta</code><span><a class="mark" href="#esm_import_meta" id="esm_import_meta">#</a></span></h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>The <code>import.meta</code> metaproperty is an <code>Object</code> that contains the following
property:</p>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The absolute <code>file:</code> URL of the module.</li>
</ul>
<h2>Differences between ES modules and CommonJS<span><a class="mark" href="#esm_differences_between_es_modules_and_commonjs" id="esm_differences_between_es_modules_and_commonjs">#</a></span></h2>
<h3>Mandatory file extensions<span><a class="mark" href="#esm_mandatory_file_extensions" id="esm_mandatory_file_extensions">#</a></span></h3>
<p>A file extension must be provided when using the <code>import</code> keyword. Directory
indexes (e.g. <code>'./startup/index.js'</code>) must also be fully specified.</p>
<p>This behavior matches how <code>import</code> behaves in browser environments, assuming a
typically configured server.</p>
<h3>No <code>NODE_PATH</code><span><a class="mark" href="#esm_no_node_path" id="esm_no_node_path">#</a></span></h3>
<p><code>NODE_PATH</code> is not part of resolving <code>import</code> specifiers. Please use symlinks
if this behavior is desired.</p>
<h3>No <code>require</code>, <code>exports</code>, <code>module.exports</code>, <code>__filename</code>, <code>__dirname</code><span><a class="mark" href="#esm_no_require_exports_module_exports_filename_dirname" id="esm_no_require_exports_module_exports_filename_dirname">#</a></span></h3>
<p>These CommonJS variables are not available in ES modules.</p>
<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>
<p>Equivalents of <code>__filename</code> and <code>__dirname</code> can be created inside of each file
via <a href="#esm_import_meta"><code>import.meta.url</code></a>.</p>
<pre><code class="language-js">import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
</code></pre>
<h3>No <code>require.resolve</code><span><a class="mark" href="#esm_no_require_resolve" id="esm_no_require_resolve">#</a></span></h3>
<p>Former use cases relying on <code>require.resolve</code> to determine the resolved path
of a module can be supported via <code>import.meta.resolve</code>, which is experimental
and supported via the <code>--experimental-import-meta-resolve</code> flag:</p>
<pre><code class="language-js">(async () => {
  const dependencyAsset = await import.meta.resolve('component-lib/asset.css');
})();
</code></pre>
<p><code>import.meta.resolve</code> also accepts a second argument which is the parent module
from which to resolve from:</p>
<pre><code class="language-js">(async () => {
  // Equivalent to import.meta.resolve('./dep')
  await import.meta.resolve('./dep', import.meta.url);
})();
</code></pre>
<p>This function is asynchronous since the ES module resolver in Node.js is
asynchronous. With the introduction of <a href="https://github.com/tc39/proposal-top-level-await">Top-Level Await</a>, these use cases
will be easier as they won't require an async function wrapper.</p>
<h3>No <code>require.extensions</code><span><a class="mark" href="#esm_no_require_extensions" id="esm_no_require_extensions">#</a></span></h3>
<p><code>require.extensions</code> is not used by <code>import</code>. The expectation is that loader
hooks can provide this workflow in the future.</p>
<h3>No <code>require.cache</code><span><a class="mark" href="#esm_no_require_cache" id="esm_no_require_cache">#</a></span></h3>
<p><code>require.cache</code> is not used by <code>import</code>. It has a separate cache.</p>
<h3>URL-based paths<span><a class="mark" href="#esm_url_based_paths" id="esm_url_based_paths">#</a></span></h3>
<p>ES modules are resolved and cached based upon
<a href="https://url.spec.whatwg.org/">URL</a> semantics. This means that files containing
special characters such as <code>#</code> and <code>?</code> need to be escaped.</p>
<p>Modules will be loaded multiple times if the <code>import</code> specifier used to resolve
them have a different query or fragment.</p>
<pre><code class="language-js">import './foo.mjs?query=1'; // loads ./foo.mjs with query of "?query=1"
import './foo.mjs?query=2'; // loads ./foo.mjs with query of "?query=2"
</code></pre>
<p>For now, only modules using the <code>file:</code> protocol can be loaded.</p>
<h2>Interoperability with CommonJS<span><a class="mark" href="#esm_interoperability_with_commonjs" id="esm_interoperability_with_commonjs">#</a></span></h2>
<h3><code>require</code><span><a class="mark" href="#esm_require" id="esm_require">#</a></span></h3>
<p><code>require</code> always treats the files it references as CommonJS. This applies
whether <code>require</code> is used the traditional way within a CommonJS environment, or
in an ES module environment using <a href="modules.html#modules_module_createrequire_filename"><code>module.createRequire()</code></a>.</p>
<p>To include an ES module into CommonJS, use <a href="#esm_import_expressions"><code>import()</code></a>.</p>
<h3><code>import</code> statements<span><a class="mark" href="#esm_import_statements" id="esm_import_statements">#</a></span></h3>
<p>An <code>import</code> statement can reference an ES module or a CommonJS module. Other
file types such as JSON or native modules are not supported. For those, use
<a href="modules.html#modules_module_createrequire_filename"><code>module.createRequire()</code></a>.</p>
<p><code>import</code> statements are permitted only in ES modules. For similar functionality
in CommonJS, see <a href="#esm_import_expressions"><code>import()</code></a>.</p>
<p>The <em>specifier</em> of an <code>import</code> statement (the string after the <code>from</code> keyword)
can either be an URL-style relative path like <code>'./file.mjs'</code> or a package name
like <code>'fs'</code>.</p>
<p>Like in CommonJS, files within packages can be accessed by appending a path to
the package name; unless the package’s <code>package.json</code> contains an <code>"exports"</code>
field, in which case files within packages need to be accessed via the path
defined in <code>"exports"</code>.</p>
<pre><code class="language-js">import { sin, cos } from 'geometry/trigonometry-functions.mjs';
</code></pre>
<p>Only the “default export” is supported for CommonJS files or packages:</p>
<!-- eslint-disable no-duplicate-imports -->
<pre><code class="language-js">import packageMain from 'commonjs-package'; // Works

import { method } from 'commonjs-package'; // Errors
</code></pre>
<p>It is also possible to
<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>
<h3><code>import()</code> expressions<span><a class="mark" href="#esm_import_expressions" id="esm_import_expressions">#</a></span></h3>
<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
used to include ES module files from CommonJS code.</p>
<h2>CommonJS, JSON, and native modules<span><a class="mark" href="#esm_commonjs_json_and_native_modules" id="esm_commonjs_json_and_native_modules">#</a></span></h2>
<p>CommonJS, JSON, and native modules can be used with
<a href="modules.html#modules_module_createrequire_filename"><code>module.createRequire()</code></a>.</p>
<pre><code class="language-js">// cjs.cjs
module.exports = 'cjs';

// esm.mjs
import { createRequire } from 'module';

const require = createRequire(import.meta.url);

const cjs = require('./cjs.cjs');
cjs === 'cjs'; // true
</code></pre>
<h2>Builtin modules<span><a class="mark" href="#esm_builtin_modules" id="esm_builtin_modules">#</a></span></h2>
<p>Builtin modules will provide named exports of their public API. A
default export is also provided which is the value of the CommonJS exports.
The default export can be used for, among other things, modifying the named
exports. Named exports of builtin modules are updated only by calling
<a href="modules.html#modules_module_syncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a>.</p>
<pre><code class="language-js">import EventEmitter from 'events';
const e = new EventEmitter();
</code></pre>
<pre><code class="language-js">import { readFile } from 'fs';
readFile('./foo.txt', (err, source) => {
  if (err) {
    console.error(err);
  } else {
    console.log(source);
  }
});
</code></pre>
<pre><code class="language-js">import fs, { readFileSync } from 'fs';
import { syncBuiltinESMExports } from 'module';

fs.readFileSync = () => Buffer.from('Hello, ESM');
syncBuiltinESMExports();

fs.readFileSync === readFileSync;
</code></pre>
<h2>Experimental JSON modules<span><a class="mark" href="#esm_experimental_json_modules" id="esm_experimental_json_modules">#</a></span></h2>
<p>Currently importing JSON modules are only supported in the <code>commonjs</code> mode
and are loaded using the CJS loader. <a href="https://html.spec.whatwg.org/#creating-a-json-module-script">WHATWG JSON modules specification</a> are
still being standardized, and are experimentally supported by including the
additional flag <code>--experimental-json-modules</code> when running Node.js.</p>
<p>When the <code>--experimental-json-modules</code> flag is included both the
<code>commonjs</code> and <code>module</code> mode will use the new experimental JSON
loader. The imported JSON only exposes a <code>default</code>, there is no
support for named exports. A cache entry is created in the CommonJS
cache, to avoid duplication. The same object will be returned in
CommonJS if the JSON module has already been imported from the
same path.</p>
<p>Assuming an <code>index.mjs</code> with</p>
<!-- eslint-skip -->
<pre><code class="language-js">import packageConfig from './package.json';
</code></pre>
<p>The <code>--experimental-json-modules</code> flag is needed for the module
to work.</p>
<pre><code class="language-bash">node index.mjs # fails
node --experimental-json-modules index.mjs # works
</code></pre>
<h2>Experimental Wasm modules<span><a class="mark" href="#esm_experimental_wasm_modules" id="esm_experimental_wasm_modules">#</a></span></h2>
<p>Importing Web Assembly modules is supported under the
<code>--experimental-wasm-modules</code> flag, allowing any <code>.wasm</code> files to be
imported as normal modules while also supporting their module imports.</p>
<p>This integration is in line with the
<a href="https://github.com/webassembly/esm-integration">ES Module Integration Proposal for Web Assembly</a>.</p>
<p>For example, an <code>index.mjs</code> containing:</p>
<pre><code class="language-js">import * as M from './module.wasm';
console.log(M);
</code></pre>
<p>executed under:</p>
<pre><code class="language-bash">node --experimental-wasm-modules index.mjs
</code></pre>
<p>would provide the exports interface for the instantiation of <code>module.wasm</code>.</p>
<h2>Experimental loaders<span><a class="mark" href="#esm_experimental_loaders" id="esm_experimental_loaders">#</a></span></h2>
<p><strong>Note: This API is currently being redesigned and will still change.</strong></p>

<p>To customize the default module resolution, loader hooks can optionally be
provided via a <code>--experimental-loader ./loader-name.mjs</code> argument to Node.js.</p>
<p>When hooks are used they only apply to ES module loading and not to any
CommonJS modules loaded.</p>
<h3>Hooks<span><a class="mark" href="#esm_hooks" id="esm_hooks">#</a></span></h3>
<h4><code>resolve</code> hook<span><a class="mark" href="#esm_code_resolve_code_hook" id="esm_code_resolve_code_hook">#</a></span></h4>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>The <code>resolve</code> hook returns the resolved file URL for a given module specifier
and parent URL. The module specifier is the string in an <code>import</code> statement or
<code>import()</code> expression, and the parent URL is the URL of the module that imported
this one, or <code>undefined</code> if this is the main entry point for the application.</p>
<p>The <code>conditions</code> property on the <code>context</code> is an array of conditions for
<a href="#esm_conditional_exports">Conditional exports</a> that apply to this resolution request. They can be used
for looking up conditional mappings elsewhere or to modify the list when calling
the default resolution logic.</p>
<p>The <a href="#esm_conditional_exports">current set of Node.js default conditions</a> will always
be in the <code>context.conditions</code> list passed to the hook. If the hook wants to
ensure Node.js-compatible resolution logic, all items from this default
condition list <strong>must</strong> be passed through to the <code>defaultResolve</code> function.</p>
<pre><code class="language-js">/**
 * @param {string} specifier
 * @param {{
 *   parentURL: !(string | undefined),
 *   conditions: !(Array&#x3C;string>),
 * }} context
 * @param {Function} defaultResolve
 * @returns {!(Promise&#x3C;{ url: string }>)}
 */
export async function resolve(specifier, context, defaultResolve) {
  const { parentURL = null } = context;
  if (Math.random() > 0.5) { // Some condition.
    // For some or all specifiers, do some custom logic for resolving.
    // Always return an object of the form {url: &#x3C;string>}.
    return {
      url: parentURL ?
        new URL(specifier, parentURL).href :
        new URL(specifier).href,
    };
  }
  if (Math.random() &#x3C; 0.5) { // Another condition.
    // When calling `defaultResolve`, the arguments can be modified. In this
    // case it's adding another value for matching conditional exports.
    return defaultResolve(specifier, {
      ...context,
      conditions: [...context.conditions, 'another-condition'],
    });
  }
  // Defer to Node.js for all other specifiers.
  return defaultResolve(specifier, context, defaultResolve);
}
</code></pre>
<h4><code>getFormat</code> hook<span><a class="mark" href="#esm_code_getformat_code_hook" id="esm_code_getformat_code_hook">#</a></span></h4>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>The <code>getFormat</code> hook provides a way to define a custom method of determining how
a URL should be interpreted. The <code>format</code> returned also affects what the
acceptable forms of source values are for a module when parsing. This can be one
of the following:</p>








































<table><thead><tr><th><code>format</code></th><th>Description</th><th>Acceptable Types For <code>source</code> Returned by <code>getSource</code> or <code>transformSource</code></th></tr></thead><tbody><tr><td><code>'builtin'</code></td><td>Load a Node.js builtin module</td><td>Not applicable</td></tr><tr><td><code>'commonjs'</code></td><td>Load a Node.js CommonJS module</td><td>Not applicable</td></tr><tr><td><code>'dynamic'</code></td><td>Use a <a href="#esm_code_dynamicinstantiate_code_hook">dynamic instantiate hook</a></td><td>Not applicable</td></tr><tr><td><code>'json'</code></td><td>Load a JSON file</td><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></tr><tr><td><code>'module'</code></td><td>Load an ES module</td><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></tr><tr><td><code>'wasm'</code></td><td>Load a WebAssembly module</td><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></tr></tbody></table>
<p>Note: These types all correspond to classes defined in ECMAScript.</p>
<ul>
<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>
<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>
<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>
</ul>
<p>Note: If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>) is
not a string, it will be converted to a string using <a href="util.html#util_class_util_textdecoder"><code>util.TextDecoder</code></a>.</p>
<pre><code class="language-js">/**
 * @param {string} url
 * @param {Object} context (currently empty)
 * @param {Function} defaultGetFormat
 * @returns {Promise&#x3C;{ format: string }>}
 */
export async function getFormat(url, context, defaultGetFormat) {
  if (Math.random() > 0.5) { // Some condition.
    // For some or all URLs, do some custom logic for determining format.
    // Always return an object of the form {format: &#x3C;string>}, where the
    // format is one of the strings in the table above.
    return {
      format: 'module',
    };
  }
  // Defer to Node.js for all other URLs.
  return defaultGetFormat(url, context, defaultGetFormat);
}
</code></pre>
<h4><code>getSource</code> hook<span><a class="mark" href="#esm_code_getsource_code_hook" id="esm_code_getsource_code_hook">#</a></span></h4>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>The <code>getSource</code> hook provides a way to define a custom method for retrieving
the source code of an ES module specifier. This would allow a loader to
potentially avoid reading files from disk.</p>
<pre><code class="language-js">/**
 * @param {string} url
 * @param {{ format: string }} context
 * @param {Function} defaultGetSource
 * @returns {Promise&#x3C;{ source: !(SharedArrayBuffer | string | Uint8Array) }>}
 */
export async function getSource(url, context, defaultGetSource) {
  const { format } = context;
  if (Math.random() > 0.5) { // Some condition.
    // For some or all URLs, do some custom logic for retrieving the source.
    // Always return an object of the form {source: &#x3C;string|buffer>}.
    return {
      source: '...',
    };
  }
  // Defer to Node.js for all other URLs.
  return defaultGetSource(url, context, defaultGetSource);
}
</code></pre>
<h4><code>transformSource</code> hook<span><a class="mark" href="#esm_code_transformsource_code_hook" id="esm_code_transformsource_code_hook">#</a></span></h4>
<pre><code class="language-console">NODE_OPTIONS='--experimental-loader ./custom-loader.mjs' node x.js
</code></pre>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>The <code>transformSource</code> hook provides a way to modify the source code of a loaded
ES module file after the source string has been loaded but before Node.js has
done anything with it.</p>
<p>If this hook is used to convert unknown-to-Node.js file types into executable
JavaScript, a resolve hook is also necessary in order to register any
unknown-to-Node.js file extensions. See the <a href="#esm_transpiler_loader">transpiler loader example</a> below.</p>
<pre><code class="language-js">/**
 * @param {!(SharedArrayBuffer | string | Uint8Array)} source
 * @param {{
 *   url: string,
 *   format: string,
 * }} context
 * @param {Function} defaultTransformSource
 * @returns {Promise&#x3C;{ source: !(SharedArrayBuffer | string | Uint8Array) }>}
 */
export async function transformSource(source, context, defaultTransformSource) {
  const { url, format } = context;
  if (Math.random() > 0.5) { // Some condition.
    // For some or all URLs, do some custom logic for modifying the source.
    // Always return an object of the form {source: &#x3C;string|buffer>}.
    return {
      source: '...',
    };
  }
  // Defer to Node.js for all other sources.
  return defaultTransformSource(source, context, defaultTransformSource);
}
</code></pre>
<h4><code>getGlobalPreloadCode</code> hook<span><a class="mark" href="#esm_code_getglobalpreloadcode_code_hook" id="esm_code_getglobalpreloadcode_code_hook">#</a></span></h4>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>Sometimes it can be necessary to run some code inside of the same global scope
that the application will run in. This hook allows to return a string that will
be ran as sloppy-mode script on startup.</p>
<p>Similar to how CommonJS wrappers work, the code runs in an implicit function
scope. The only argument is a <code>require</code>-like function that can be used to load
builtins like "fs": <code>getBuiltin(request: string)</code>.</p>
<p>If the code needs more advanced <code>require</code> features, it will have to construct
its own <code>require</code> using  <code>module.createRequire()</code>.</p>
<pre><code class="language-js">/**
 * @returns {string} Code to run before application startup
 */
export function getGlobalPreloadCode() {
  return `\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');

const { createRequire } = getBuiltin('module');

const require = createRequire(process.cwd() + '/&#x3C;preload>');
// [...]
`;
}
</code></pre>
<h4><code>dynamicInstantiate</code> hook<span><a class="mark" href="#esm_code_dynamicinstantiate_code_hook" id="esm_code_dynamicinstantiate_code_hook">#</a></span></h4>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>To create a custom dynamic module that doesn't correspond to one of the
existing <code>format</code> interpretations, the <code>dynamicInstantiate</code> hook can be used.
This hook is called only for modules that return <code>format: 'dynamic'</code> from
the <a href="#esm_code_getformat_code_hook"><code>getFormat</code> hook</a>.</p>
<pre><code class="language-js">/**
 * @param {string} url
 * @returns {object} response
 * @returns {array} response.exports
 * @returns {function} response.execute
 */
export async function dynamicInstantiate(url) {
  return {
    exports: ['customExportName'],
    execute: (exports) => {
      // Get and set functions provided for pre-allocated export names
      exports.customExportName.set('value');
    }
  };
}
</code></pre>
<p>With the list of module exports provided upfront, the <code>execute</code> function will
then be called at the exact point of module evaluation order for that module
in the import tree.</p>
<h3>Examples<span><a class="mark" href="#esm_examples" id="esm_examples">#</a></span></h3>
<p>The various loader hooks can be used together to accomplish wide-ranging
customizations of Node.js’ code loading and evaluation behaviors.</p>
<h4>HTTPS loader<span><a class="mark" href="#esm_https_loader" id="esm_https_loader">#</a></span></h4>
<p>In current Node.js, specifiers starting with <code>https://</code> are unsupported. The
loader below registers hooks to enable rudimentary support for such specifiers.
While this may seem like a significant improvement to Node.js core
functionality, there are substantial downsides to actually using this loader:
performance is much slower than loading files from disk, there is no caching,
and there is no security.</p>
<pre><code class="language-js">// https-loader.mjs
import { get } from 'https';

export function resolve(specifier, context, defaultResolve) {
  const { parentURL = null } = context;

  // Normally Node.js would error on specifiers starting with 'https://', so
  // this hook intercepts them and converts them into absolute URLs to be
  // passed along to the later hooks below.
  if (specifier.startsWith('https://')) {
    return {
      url: specifier
    };
  } else if (parentURL &#x26;&#x26; parentURL.startsWith('https://')) {
    return {
      url: new URL(specifier, parentURL).href
    };
  }

  // Let Node.js handle all other specifiers.
  return defaultResolve(specifier, context, defaultResolve);
}

export function getFormat(url, context, defaultGetFormat) {
  // This loader assumes all network-provided JavaScript is ES module code.
  if (url.startsWith('https://')) {
    return {
      format: 'module'
    };
  }

  // Let Node.js handle all other URLs.
  return defaultGetFormat(url, context, defaultGetFormat);
}

export function getSource(url, context, defaultGetSource) {
  // For JavaScript to be loaded over the network, we need to fetch and
  // return it.
  if (url.startsWith('https://')) {
    return new Promise((resolve, reject) => {
      get(url, (res) => {
        let data = '';
        res.on('data', (chunk) => data += chunk);
        res.on('end', () => resolve({ source: data }));
      }).on('error', (err) => reject(err));
    });
  }

  // Let Node.js handle all other URLs.
  return defaultGetSource(url, context, defaultGetSource);
}
</code></pre>
<pre><code class="language-js">// main.mjs
import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';

console.log(VERSION);
</code></pre>
<p>With this loader, running:</p>
<pre><code class="language-console">node --experimental-loader ./https-loader.mjs ./main.js
</code></pre>
<p>Will print the current version of CoffeeScript per the module at the URL in
<code>main.mjs</code>.</p>
<h4>Transpiler loader<span><a class="mark" href="#esm_transpiler_loader" id="esm_transpiler_loader">#</a></span></h4>
<p>Sources that are in formats Node.js doesn’t understand can be converted into
JavaScript using the <a href="#esm_code_transformsource_code_hook"><code>transformSource</code> hook</a>. Before that hook gets called,
however, other hooks need to tell Node.js not to throw an error on unknown file
types; and to tell Node.js how to load this new file type.</p>
<p>This is less performant than transpiling source files before running
Node.js; a transpiler loader should only be used for development and testing
purposes.</p>
<pre><code class="language-js">// coffeescript-loader.mjs
import { URL, pathToFileURL } from 'url';
import CoffeeScript from 'coffeescript';

const baseURL = pathToFileURL(`${process.cwd()}/`).href;

// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.
const extensionsRegex = /\.coffee$|\.litcoffee$|\.coffee\.md$/;

export function resolve(specifier, context, defaultResolve) {
  const { parentURL = baseURL } = context;

  // Node.js normally errors on unknown file extensions, so return a URL for
  // specifiers ending in the CoffeeScript file extensions.
  if (extensionsRegex.test(specifier)) {
    return {
      url: new URL(specifier, parentURL).href
    };
  }

  // Let Node.js handle all other specifiers.
  return defaultResolve(specifier, context, defaultResolve);
}

export function getFormat(url, context, defaultGetFormat) {
  // Now that we patched resolve to let CoffeeScript URLs through, we need to
  // tell Node.js what format such URLs should be interpreted as. For the
  // purposes of this loader, all CoffeeScript URLs are ES modules.
  if (extensionsRegex.test(url)) {
    return {
      format: 'module'
    };
  }

  // Let Node.js handle all other URLs.
  return defaultGetFormat(url, context, defaultGetFormat);
}

export function transformSource(source, context, defaultTransformSource) {
  const { url, format } = context;

  if (extensionsRegex.test(url)) {
    return {
      source: CoffeeScript.compile(source, { bare: true })
    };
  }

  // Let Node.js handle all other sources.
  return defaultTransformSource(source, context, defaultTransformSource);
}
</code></pre>
<pre><code class="language-coffee"># main.coffee
import { scream } from './scream.coffee'
console.log scream 'hello, world'

import { version } from 'process'
console.log "Brought to you by Node.js version #{version}"
</code></pre>
<pre><code class="language-coffee"># scream.coffee
export scream = (str) -> str.toUpperCase()
</code></pre>
<p>With this loader, running:</p>
<pre><code class="language-console">node --experimental-loader ./coffeescript-loader.mjs main.coffee
</code></pre>
<p>Will cause <code>main.coffee</code> to be turned into JavaScript after its source code is
loaded from disk but before Node.js executes it; and so on for any <code>.coffee</code>,
<code>.litcoffee</code> or <code>.coffee.md</code> files referenced via <code>import</code> statements of any
loaded file.</p>
<h2>Resolution algorithm<span><a class="mark" href="#esm_resolution_algorithm" id="esm_resolution_algorithm">#</a></span></h2>
<h3>Features<span><a class="mark" href="#esm_features" id="esm_features">#</a></span></h3>
<p>The resolver has the following properties:</p>
<ul>
<li>FileURL-based resolution as is used by ES modules</li>
<li>Support for builtin module loading</li>
<li>Relative and absolute URL resolution</li>
<li>No default extensions</li>
<li>No folder mains</li>
<li>Bare specifier package resolution lookup through node_modules</li>
</ul>
<h3>Resolver algorithm<span><a class="mark" href="#esm_resolver_algorithm" id="esm_resolver_algorithm">#</a></span></h3>
<p>The algorithm to load an ES module specifier is given through the
<strong>ESM_RESOLVE</strong> method below. It returns the resolved URL for a
module specifier relative to a parentURL.</p>
<p>The algorithm to determine the module format of a resolved URL is
provided by <strong>ESM_FORMAT</strong>, which returns the unique module
format for any file. The <em>"module"</em> format is returned for an ECMAScript
Module, while the <em>"commonjs"</em> format is used to indicate loading through the
legacy CommonJS loader. Additional formats such as <em>"addon"</em> can be extended in
future updates.</p>
<p>In the following algorithms, all subroutine errors are propagated as errors
of these top-level routines unless stated otherwise.</p>
<p><em>defaultEnv</em> is the conditional environment name priority array,
<code>["node", "import"]</code>.</p>
<p>The resolver can throw the following errors:</p>
<ul>
<li><em>Invalid Module Specifier</em>: Module specifier is an invalid URL, package name
or package subpath specifier.</li>
<li><em>Invalid Package Configuration</em>: package.json configuration is invalid or
contains an invalid configuration.</li>
<li><em>Invalid Package Target</em>: Package exports define a target module within the
package that is an invalid type or string target.</li>
<li><em>Package Path Not Exported</em>: Package exports do not define or permit a target
subpath in the package for the given module.</li>
<li><em>Module Not Found</em>: The package or module requested does not exist.</li>
</ul>
<details>
<summary>Resolver algorithm specification</summary>
<p><strong>ESM_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>resolvedURL</em> be <strong>undefined</strong>.</li>
<li>
<p>If <em>specifier</em> is a valid URL, then</p>
<ol>
<li>Set <em>resolvedURL</em> to the result of parsing and reserializing
<em>specifier</em> as a URL.</li>
</ol>
</li>
<li>
<p>Otherwise, if <em>specifier</em> starts with <em>"/"</em>, then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>
<p>Otherwise, if <em>specifier</em> starts with <em>"./"</em> or <em>"../"</em>, then</p>
<ol>
<li>Set <em>resolvedURL</em> to the URL resolution of <em>specifier</em> relative to
<em>parentURL</em>.</li>
</ol>
</li>
<li>
<p>Otherwise,</p>
<ol>
<li>Note: <em>specifier</em> is now a bare specifier.</li>
<li>Set <em>resolvedURL</em> the result of
<strong>PACKAGE_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>).</li>
</ol>
</li>
<li>
<p>If <em>resolvedURL</em> contains any percent encodings of <em>"/"</em> or <em>"\"</em> (<em>"%2f"</em>
and <em>"%5C"</em> respectively), then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>
<p>If the file at <em>resolvedURL</em> is a directory, then</p>
<ol>
<li>Throw an <em>Unsupported Directory Import</em> error.</li>
</ol>
</li>
<li>
<p>If the file at <em>resolvedURL</em> does not exist, then</p>
<ol>
<li>Throw a <em>Module Not Found</em> error.</li>
</ol>
</li>
<li>Set <em>resolvedURL</em> to the real path of <em>resolvedURL</em>.</li>
<li>Let <em>format</em> be the result of <strong>ESM_FORMAT</strong>(<em>resolvedURL</em>).</li>
<li>Load <em>resolvedURL</em> as module format, <em>format</em>.</li>
<li>Return <em>resolvedURL</em>.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_RESOLVE</strong>(<em>packageSpecifier</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>packageName</em> be <em>undefined</em>.</li>
<li>Let <em>packageSubpath</em> be <em>undefined</em>.</li>
<li>
<p>If <em>packageSpecifier</em> is an empty string, then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>
<p>Otherwise,</p>
<ol>
<li>
<p>If <em>packageSpecifier</em> does not contain a <em>"/"</em> separator, then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Set <em>packageName</em> to the substring of <em>packageSpecifier</em>
until the second <em>"/"</em> separator or the end of the string.</li>
</ol>
</li>
<li>
<p>If <em>packageName</em> starts with <em>"."</em> or contains <em>"\"</em> or <em>"%"</em>, then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Let <em>packageSubpath</em> be <em>undefined</em>.</li>
<li>
<p>If the length of <em>packageSpecifier</em> is greater than the length of
<em>packageName</em>, then</p>
<ol>
<li>Set <em>packageSubpath</em> to <em>"."</em> concatenated with the substring of
<em>packageSpecifier</em> from the position at the length of <em>packageName</em>.</li>
</ol>
</li>
<li>
<p>If <em>packageSubpath</em> contains any <em>"."</em> or <em>".."</em> segments or percent
encoded strings for <em>"/"</em> or <em>"\"</em>, then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Set <em>selfUrl</em> to the result of
<strong>SELF_REFERENCE_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>).</li>
<li>If <em>selfUrl</em> isn't empty, return <em>selfUrl</em>.</li>
<li>
<p>If <em>packageSubpath</em> is <em>undefined</em> and <em>packageName</em> is a Node.js builtin
module, then</p>
<ol>
<li>Return the string <em>"nodejs:"</em> concatenated with <em>packageSpecifier</em>.</li>
</ol>
</li>
<li>
<p>While <em>parentURL</em> is not the file system root,</p>
<ol>
<li>Let <em>packageURL</em> be the URL resolution of <em>"node_modules/"</em>
concatenated with <em>packageSpecifier</em>, relative to <em>parentURL</em>.</li>
<li>Set <em>parentURL</em> to the parent folder URL of <em>parentURL</em>.</li>
<li>
<p>If the folder at <em>packageURL</em> does not exist, then</p>
<ol>
<li>Set <em>parentURL</em> to the parent URL path of <em>parentURL</em>.</li>
<li>Continue the next loop iteration.</li>
</ol>
</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
<li>
<p>If <em>packageSubpath</em> is equal to <em>"./"</em>, then</p>
<ol>
<li>Return <em>packageURL</em> + <em>"/"</em>.</li>
</ol>
</li>
<li>
<p>If <em>packageSubpath</em> is _undefined__, then</p>
<ol>
<li>Return the result of <strong>PACKAGE_MAIN_RESOLVE</strong>(<em>packageURL</em>,
<em>pjson</em>).</li>
</ol>
</li>
<li>
<p>Otherwise,</p>
<ol>
<li>
<p>If <em>pjson</em> is not <strong>null</strong> and <em>pjson</em> has an <em>"exports"</em> key, then</p>
<ol>
<li>Let <em>exports</em> be <em>pjson.exports</em>.</li>
<li>
<p>If <em>exports</em> is not <strong>null</strong> or <strong>undefined</strong>, then</p>
<ol>
<li>Return <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>,
<em>packageSubpath</em>, <em>pjson.exports</em>).</li>
</ol>
</li>
</ol>
</li>
<li>Return the URL resolution of <em>packageSubpath</em> in <em>packageURL</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Throw a <em>Module Not Found</em> error.</li>
</ol>
</blockquote>
<p><strong>SELF_REFERENCE_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>packageURL</em> be the result of <strong>READ_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li>
<li>
<p>If <em>packageURL</em> is <strong>null</strong>, then</p>
<ol>
<li>Return <strong>undefined</strong>.</li>
</ol>
</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
<li>
<p>If <em>pjson</em> does not include an <em>"exports"</em> property, then</p>
<ol>
<li>Return <strong>undefined</strong>.</li>
</ol>
</li>
<li>
<p>If <em>pjson.name</em> is equal to <em>packageName</em>, then</p>
<ol>
<li>
<p>If <em>packageSubpath</em> is equal to <em>"./"</em>, then</p>
<ol>
<li>Return <em>packageURL</em> + <em>"/"</em>.</li>
</ol>
</li>
<li>
<p>If <em>packageSubpath</em> is <em>undefined</em>, then</p>
<ol>
<li>Return the result of <strong>PACKAGE_MAIN_RESOLVE</strong>(<em>packageURL</em>, <em>pjson</em>).</li>
</ol>
</li>
<li>
<p>Otherwise,</p>
<ol>
<li>
<p>If <em>pjson</em> is not <strong>null</strong> and <em>pjson</em> has an <em>"exports"</em> key, then</p>
<ol>
<li>Let <em>exports</em> be <em>pjson.exports</em>.</li>
<li>
<p>If <em>exports</em> is not <strong>null</strong> or <strong>undefined</strong>, then</p>
<ol>
<li>Return <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>subpath</em>,
<em>pjson.exports</em>).</li>
</ol>
</li>
</ol>
</li>
<li>Return the URL resolution of <em>subpath</em> in <em>packageURL</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Otherwise, return <strong>undefined</strong>.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_MAIN_RESOLVE</strong>(<em>packageURL</em>, <em>pjson</em>)</p>
<blockquote>
<ol>
<li>
<p>If <em>pjson</em> is <strong>null</strong>, then</p>
<ol>
<li>Throw a <em>Module Not Found</em> error.</li>
</ol>
</li>
<li>
<p>If <em>pjson.exports</em> is not <strong>null</strong> or <strong>undefined</strong>, then</p>
<ol>
<li>If <em>exports</em> is an Object with both a key starting with <em>"."</em> and a key
not starting with <em>"."</em>, throw an <em>Invalid Package Configuration</em> error.</li>
<li>
<p>If <em>pjson.exports</em> is a String or Array, or an Object containing no
keys starting with <em>"."</em>, then</p>
<ol>
<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>,
<em>pjson.exports</em>, <em>""</em>).</li>
</ol>
</li>
<li>
<p>If <em>pjson.exports</em> is an Object containing a <em>"."</em> property, then</p>
<ol>
<li>Let <em>mainExport</em> be the <em>"."</em> property in <em>pjson.exports</em>.</li>
<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>,
<em>mainExport</em>, <em>""</em>).</li>
</ol>
</li>
<li>Throw a <em>Package Path Not Exported</em> error.</li>
</ol>
</li>
<li>Let <em>legacyMainURL</em> be the result applying the legacy
<strong>LOAD_AS_DIRECTORY</strong> CommonJS resolver to <em>packageURL</em>, throwing a
<em>Module Not Found</em> error for no resolution.</li>
<li>Return <em>legacyMainURL</em>.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>packagePath</em>, <em>exports</em>)</p>
<blockquote>
<ol>
<li>If <em>exports</em> is an Object with both a key starting with <em>"."</em> and a key not
starting with <em>"."</em>, throw an <em>Invalid Package Configuration</em> error.</li>
<li>
<p>If <em>exports</em> is an Object and all keys of <em>exports</em> start with <em>"."</em>, then</p>
<ol>
<li>Set <em>packagePath</em> to <em>"./"</em> concatenated with <em>packagePath</em>.</li>
<li>
<p>If <em>packagePath</em> is a key of <em>exports</em>, then</p>
<ol>
<li>Let <em>target</em> be the value of <em>exports[packagePath]</em>.</li>
<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>,
<em>""</em>, <em>defaultEnv</em>).</li>
</ol>
</li>
<li>Let <em>directoryKeys</em> be the list of keys of <em>exports</em> ending in
<em>"/"</em>, sorted by length descending.</li>
<li>
<p>For each key <em>directory</em> in <em>directoryKeys</em>, do</p>
<ol>
<li>
<p>If <em>packagePath</em> starts with <em>directory</em>, then</p>
<ol>
<li>Let <em>target</em> be the value of <em>exports[directory]</em>.</li>
<li>Let <em>subpath</em> be the substring of <em>target</em> starting at the index
of the length of <em>directory</em>.</li>
<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>,
<em>subpath</em>, <em>defaultEnv</em>).</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li>Throw a <em>Package Path Not Exported</em> error.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>, <em>subpath</em>, <em>env</em>)</p>
<blockquote>
<ol>
<li>
<p>If <em>target</em> is a String, then</p>
<ol>
<li>If <em>target</em> does not start with <em>"./"</em> or contains any <em>"node_modules"</em>
segments including <em>"node_modules"</em> percent-encoding, throw an
<em>Invalid Package Target</em> error.</li>
<li>Let <em>resolvedTarget</em> be the URL resolution of the concatenation of
<em>packageURL</em> and <em>target</em>.</li>
<li>If <em>resolvedTarget</em> is not contained in <em>packageURL</em>, throw an
<em>Invalid Package Target</em> error.</li>
<li>If <em>subpath</em> has non-zero length and <em>target</em> does not end with <em>"/"</em>,
throw an <em>Invalid Module Specifier</em> error.</li>
<li>Let <em>resolved</em> be the URL resolution of the concatenation of
<em>subpath</em> and <em>resolvedTarget</em>.</li>
<li>If <em>resolved</em> is not contained in <em>resolvedTarget</em>, throw an
<em>Invalid Module Specifier</em> error.</li>
<li>Return <em>resolved</em>.</li>
</ol>
</li>
<li>
<p>Otherwise, if <em>target</em> is a non-null Object, then</p>
<ol>
<li>If <em>exports</em> contains any index property keys, as defined in ECMA-262
<a href="https://tc39.es/ecma262/#integer-index">6.1.7 Array Index</a>, throw an <em>Invalid Package Configuration</em> error.</li>
<li>
<p>For each property <em>p</em> of <em>target</em>, in object insertion order as,</p>
<ol>
<li>
<p>If <em>p</em> equals <em>"default"</em> or <em>env</em> contains an entry for <em>p</em>, then</p>
<ol>
<li>Let <em>targetValue</em> be the value of the <em>p</em> property in <em>target</em>.</li>
<li>Return the result of <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(
<em>packageURL</em>, <em>targetValue</em>, <em>subpath</em>, <em>env</em>), continuing the
loop on any <em>Package Path Not Exported</em> error.</li>
</ol>
</li>
</ol>
</li>
<li>Throw a <em>Package Path Not Exported</em> error.</li>
</ol>
</li>
<li>
<p>Otherwise, if <em>target</em> is an Array, then</p>
<ol>
<li>If <em>target.length is zero, throw a _Package Path Not Exported</em> error.</li>
<li>
<p>For each item <em>targetValue</em> in <em>target</em>, do</p>
<ol>
<li>If <em>targetValue</em> is an Array, continue the loop.</li>
<li>Return the result of <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>,
<em>targetValue</em>, <em>subpath</em>, <em>env</em>), continuing the loop on any
<em>Package Path Not Exported</em> or <em>Invalid Package Target</em> error.</li>
</ol>
</li>
<li>Throw the last fallback resolution error.</li>
</ol>
</li>
<li>Otherwise, if <em>target</em> is <em>null</em>, throw a <em>Package Path Not Exported</em>
error.</li>
<li>Otherwise throw an <em>Invalid Package Target</em> error.</li>
</ol>
</blockquote>
<p><strong>ESM_FORMAT</strong>(<em>url</em>)</p>
<blockquote>
<ol>
<li>Assert: <em>url</em> corresponds to an existing file.</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_SCOPE</strong>(<em>url</em>).</li>
<li>
<p>If <em>url</em> ends in <em>".mjs"</em>, then</p>
<ol>
<li>Return <em>"module"</em>.</li>
</ol>
</li>
<li>
<p>If <em>url</em> ends in <em>".cjs"</em>, then</p>
<ol>
<li>Return <em>"commonjs"</em>.</li>
</ol>
</li>
<li>
<p>If <em>pjson?.type</em> exists and is <em>"module"</em>, then</p>
<ol>
<li>
<p>If <em>url</em> ends in <em>".js"</em>, then</p>
<ol>
<li>Return <em>"module"</em>.</li>
</ol>
</li>
<li>Throw an <em>Unsupported File Extension</em> error.</li>
</ol>
</li>
<li>
<p>Otherwise,</p>
<ol>
<li>Throw an <em>Unsupported File Extension</em> error.</li>
</ol>
</li>
</ol>
</blockquote>
<p><strong>READ_PACKAGE_SCOPE</strong>(<em>url</em>)</p>
<blockquote>
<ol>
<li>Let <em>scopeURL</em> be <em>url</em>.</li>
<li>
<p>While <em>scopeURL</em> is not the file system root,</p>
<ol>
<li>If <em>scopeURL</em> ends in a <em>"node_modules"</em> path segment, return <strong>null</strong>.</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>scopeURL</em>).</li>
<li>
<p>If <em>pjson</em> is not <strong>null</strong>, then</p>
<ol>
<li>Return <em>pjson</em>.</li>
</ol>
</li>
<li>Set <em>scopeURL</em> to the parent URL of <em>scopeURL</em>.</li>
</ol>
</li>
<li>Return <strong>null</strong>.</li>
</ol>
</blockquote>
<p><strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>pjsonURL</em> be the resolution of <em>"package.json"</em> within <em>packageURL</em>.</li>
<li>
<p>If the file at <em>pjsonURL</em> does not exist, then</p>
<ol>
<li>Return <strong>null</strong>.</li>
</ol>
</li>
<li>
<p>If the file at <em>packageURL</em> does not parse as valid JSON, then</p>
<ol>
<li>Throw an <em>Invalid Package Configuration</em> error.</li>
</ol>
</li>
<li>Return the parsed JSON source of the file at <em>pjsonURL</em>.</li>
</ol>
</blockquote>
</details>
<h3>Customizing ESM specifier resolution algorithm<span><a class="mark" href="#esm_customizing_esm_specifier_resolution_algorithm" id="esm_customizing_esm_specifier_resolution_algorithm">#</a></span></h3>
<p>The current specifier resolution does not support all default behavior of
the CommonJS loader. One of the behavior differences is automatic resolution
of file extensions and the ability to import directories that have an index
file.</p>
<p>The <code>--experimental-specifier-resolution=[mode]</code> flag can be used to customize
the extension resolution algorithm. The default mode is <code>explicit</code>, which
requires the full path to a module be provided to the loader. To enable the
automatic extension resolution and importing from directories that include an
index file use the <code>node</code> mode.</p>
<pre><code class="language-bash">$ node index.mjs
success!
$ node index # Failure!
Error: Cannot find module
$ node --experimental-specifier-resolution=node index
success!
</code></pre>
      </div>
    </div>
  </div>
  <script src="assets/highlight.pack.js"></script>
  <script>document.addEventListener('DOMContentLoaded', () => { hljs.initHighlightingOnLoad(); });</script>
</body>
</html>