• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1<!DOCTYPE html>
2<html lang="en">
3<head>
4  <meta charset="utf-8">
5  <meta name="viewport" content="width=device-width">
6  <meta name="nodejs.org:node-version" content="v18.18.2">
7  <title>Modules: ECMAScript modules | Node.js v18.18.2 Documentation</title>
8  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
9  <link rel="stylesheet" href="assets/style.css">
10  <link rel="stylesheet" href="assets/hljs.css">
11  <link rel="canonical" href="https://nodejs.org/api/esm.html">
12  <script async defer src="assets/api.js" type="text/javascript"></script>
13
14</head>
15<body class="alt apidoc" id="api-section-esm">
16  <div id="content" class="clearfix">
17    <div id="column2" class="interior">
18      <div id="intro" class="interior">
19        <a href="/" title="Go back to the home page">
20          Node.js
21        </a>
22      </div>
23      <ul>
24<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
25<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
26</ul>
27<hr class="line">
28<ul>
29<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
30<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
31<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
32<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
33<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
34<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
35<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
36<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
37<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
38<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
39<li><a href="console.html" class="nav-console">Console</a></li>
40<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
41<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
42<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
43<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
44<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
45<li><a href="dns.html" class="nav-dns">DNS</a></li>
46<li><a href="domain.html" class="nav-domain">Domain</a></li>
47<li><a href="errors.html" class="nav-errors">Errors</a></li>
48<li><a href="events.html" class="nav-events">Events</a></li>
49<li><a href="fs.html" class="nav-fs">File system</a></li>
50<li><a href="globals.html" class="nav-globals">Globals</a></li>
51<li><a href="http.html" class="nav-http">HTTP</a></li>
52<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
53<li><a href="https.html" class="nav-https">HTTPS</a></li>
54<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
55<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
56<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
57<li><a href="esm.html" class="nav-esm active">Modules: ECMAScript modules</a></li>
58<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
59<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
60<li><a href="net.html" class="nav-net">Net</a></li>
61<li><a href="os.html" class="nav-os">OS</a></li>
62<li><a href="path.html" class="nav-path">Path</a></li>
63<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
64<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
65<li><a href="process.html" class="nav-process">Process</a></li>
66<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
67<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
68<li><a href="readline.html" class="nav-readline">Readline</a></li>
69<li><a href="repl.html" class="nav-repl">REPL</a></li>
70<li><a href="report.html" class="nav-report">Report</a></li>
71<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
72<li><a href="stream.html" class="nav-stream">Stream</a></li>
73<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
74<li><a href="test.html" class="nav-test">Test runner</a></li>
75<li><a href="timers.html" class="nav-timers">Timers</a></li>
76<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
77<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
78<li><a href="tty.html" class="nav-tty">TTY</a></li>
79<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
80<li><a href="url.html" class="nav-url">URL</a></li>
81<li><a href="util.html" class="nav-util">Utilities</a></li>
82<li><a href="v8.html" class="nav-v8">V8</a></li>
83<li><a href="vm.html" class="nav-vm">VM</a></li>
84<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
85<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
86<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
87<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
88<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
89</ul>
90<hr class="line">
91<ul>
92<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
93</ul>
94    </div>
95
96    <div id="column1" data-id="esm" class="interior">
97      <header class="header">
98        <div class="header-container">
99          <h1>Node.js v18.18.2 documentation</h1>
100          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
101            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
102              <path fill="none" d="M0 0h24v24H0z" />
103              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
104              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
105            </svg>
106            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
107              <path d="M0 0h24v24H0z" fill="none" />
108              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
109            </svg>
110          </button>
111        </div>
112        <div id="gtoc">
113          <ul>
114            <li class="pinned-header">Node.js v18.18.2</li>
115
116    <li class="picker-header">
117      <a href="#">
118        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
119        Table of contents
120      </a>
121
122      <div class="picker"><div class="toc"><ul>
123<li><a href="#modules-ecmascript-modules">Modules: ECMAScript modules</a>
124<ul>
125<li><a href="#introduction">Introduction</a></li>
126<li><a href="#enabling">Enabling</a></li>
127<li><a href="#packages">Packages</a></li>
128<li><a href="#import-specifiers"><code>import</code> Specifiers</a>
129<ul>
130<li><a href="#terminology">Terminology</a></li>
131<li><a href="#mandatory-file-extensions">Mandatory file extensions</a></li>
132<li><a href="#urls">URLs</a>
133<ul>
134<li><a href="#file-urls"><code>file:</code> URLs</a></li>
135<li><a href="#data-imports"><code>data:</code> imports</a></li>
136<li><a href="#node-imports"><code>node:</code> imports</a></li>
137</ul>
138</li>
139</ul>
140</li>
141<li><span class="stability_1"><a href="#import-assertions">Import assertions</a></span></li>
142<li><a href="#builtin-modules">Builtin modules</a></li>
143<li><a href="#import-expressions"><code>import()</code> expressions</a></li>
144<li><a href="#importmeta"><code>import.meta</code></a>
145<ul>
146<li><a href="#importmetaurl"><code>import.meta.url</code></a></li>
147<li><span class="stability_1"><a href="#importmetaresolvespecifier-parent"><code>import.meta.resolve(specifier[, parent])</code></a></span></li>
148</ul>
149</li>
150<li><a href="#interoperability-with-commonjs">Interoperability with CommonJS</a>
151<ul>
152<li><a href="#import-statements"><code>import</code> statements</a></li>
153<li><a href="#require"><code>require</code></a></li>
154<li><a href="#commonjs-namespaces">CommonJS Namespaces</a></li>
155<li><a href="#differences-between-es-modules-and-commonjs">Differences between ES modules and CommonJS</a>
156<ul>
157<li><a href="#no-require-exports-or-moduleexports">No <code>require</code>, <code>exports</code>, or <code>module.exports</code></a></li>
158<li><a href="#no-__filename-or-__dirname">No <code>__filename</code> or <code>__dirname</code></a></li>
159<li><a href="#no-addon-loading">No Addon Loading</a></li>
160<li><a href="#no-requireresolve">No <code>require.resolve</code></a></li>
161<li><a href="#no-node_path">No <code>NODE_PATH</code></a></li>
162<li><a href="#no-requireextensions">No <code>require.extensions</code></a></li>
163<li><a href="#no-requirecache">No <code>require.cache</code></a></li>
164</ul>
165</li>
166</ul>
167</li>
168<li><span class="stability_1"><a href="#json-modules">JSON modules</a></span></li>
169<li><span class="stability_1"><a href="#wasm-modules">Wasm modules</a></span></li>
170<li><a href="#top-level-await">Top-level <code>await</code></a></li>
171<li><span class="stability_1"><a href="#https-and-http-imports">HTTPS and HTTP imports</a></span>
172<ul>
173<li><a href="#imports-are-limited-to-http1">Imports are limited to HTTP/1</a></li>
174<li><a href="#http-is-limited-to-loopback-addresses">HTTP is limited to loopback addresses</a></li>
175<li><a href="#authentication-is-never-sent-to-the-destination-server">Authentication is never sent to the destination server.</a></li>
176<li><a href="#cors-is-never-checked-on-the-destination-server">CORS is never checked on the destination server</a></li>
177<li><a href="#cannot-load-non-network-dependencies">Cannot load non-network dependencies</a></li>
178<li><a href="#network-based-loading-is-not-enabled-by-default">Network-based loading is not enabled by default</a></li>
179</ul>
180</li>
181<li><span class="stability_1"><a href="#loaders">Loaders</a></span>
182<ul>
183<li><a href="#hooks">Hooks</a>
184<ul>
185<li><a href="#resolvespecifier-context-nextresolve"><code>resolve(specifier, context, nextResolve)</code></a></li>
186<li><a href="#loadurl-context-nextload"><code>load(url, context, nextLoad)</code></a></li>
187<li><a href="#globalpreload"><code>globalPreload()</code></a></li>
188</ul>
189</li>
190<li><a href="#examples">Examples</a>
191<ul>
192<li><a href="#https-loader">HTTPS loader</a></li>
193<li><a href="#transpiler-loader">Transpiler loader</a></li>
194<li><a href="#import-map-loader">"import map" loader</a></li>
195</ul>
196</li>
197</ul>
198</li>
199<li><a href="#resolution-and-loading-algorithm">Resolution and loading algorithm</a>
200<ul>
201<li><a href="#features">Features</a></li>
202<li><a href="#resolution-algorithm">Resolution algorithm</a></li>
203<li><a href="#resolution-algorithm-specification">Resolution Algorithm Specification</a></li>
204<li><span class="stability_1"><a href="#customizing-esm-specifier-resolution-algorithm">Customizing ESM specifier resolution algorithm</a></span></li>
205</ul>
206</li>
207</ul>
208</li>
209</ul></div></div>
210    </li>
211
212
213    <li class="picker-header">
214      <a href="#">
215        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
216        Index
217      </a>
218
219      <div class="picker"><ul>
220<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
221<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
222
223      <li>
224        <a href="index.html">Index</a>
225      </li>
226    </ul>
227
228<hr class="line">
229<ul>
230<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
231<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li>
232<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
233<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
234<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
235<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
236<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
237<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
238<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
239<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
240<li><a href="console.html" class="nav-console">Console</a></li>
241<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
242<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
243<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
244<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
245<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
246<li><a href="dns.html" class="nav-dns">DNS</a></li>
247<li><a href="domain.html" class="nav-domain">Domain</a></li>
248<li><a href="errors.html" class="nav-errors">Errors</a></li>
249<li><a href="events.html" class="nav-events">Events</a></li>
250<li><a href="fs.html" class="nav-fs">File system</a></li>
251<li><a href="globals.html" class="nav-globals">Globals</a></li>
252<li><a href="http.html" class="nav-http">HTTP</a></li>
253<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
254<li><a href="https.html" class="nav-https">HTTPS</a></li>
255<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
256<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
257<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
258<li><a href="esm.html" class="nav-esm active">Modules: ECMAScript modules</a></li>
259<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
260<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
261<li><a href="net.html" class="nav-net">Net</a></li>
262<li><a href="os.html" class="nav-os">OS</a></li>
263<li><a href="path.html" class="nav-path">Path</a></li>
264<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
265<li><a href="permissions.html" class="nav-permissions">Permissions</a></li>
266<li><a href="process.html" class="nav-process">Process</a></li>
267<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
268<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
269<li><a href="readline.html" class="nav-readline">Readline</a></li>
270<li><a href="repl.html" class="nav-repl">REPL</a></li>
271<li><a href="report.html" class="nav-report">Report</a></li>
272<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li>
273<li><a href="stream.html" class="nav-stream">Stream</a></li>
274<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
275<li><a href="test.html" class="nav-test">Test runner</a></li>
276<li><a href="timers.html" class="nav-timers">Timers</a></li>
277<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
278<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
279<li><a href="tty.html" class="nav-tty">TTY</a></li>
280<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
281<li><a href="url.html" class="nav-url">URL</a></li>
282<li><a href="util.html" class="nav-util">Utilities</a></li>
283<li><a href="v8.html" class="nav-v8">V8</a></li>
284<li><a href="vm.html" class="nav-vm">VM</a></li>
285<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
286<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
287<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li>
288<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
289<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
290</ul>
291<hr class="line">
292<ul>
293<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
294</ul></div>
295    </li>
296
297
298    <li class="picker-header">
299      <a href="#">
300        <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
301        Other versions
302      </a>
303      <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v20.x/api/esm.html">20.x</a></li>
304<li><a href="https://nodejs.org/docs/latest-v19.x/api/esm.html">19.x</a></li>
305<li><a href="https://nodejs.org/docs/latest-v18.x/api/esm.html">18.x <b>LTS</b></a></li>
306<li><a href="https://nodejs.org/docs/latest-v17.x/api/esm.html">17.x</a></li>
307<li><a href="https://nodejs.org/docs/latest-v16.x/api/esm.html">16.x</a></li>
308<li><a href="https://nodejs.org/docs/latest-v15.x/api/esm.html">15.x</a></li>
309<li><a href="https://nodejs.org/docs/latest-v14.x/api/esm.html">14.x</a></li>
310<li><a href="https://nodejs.org/docs/latest-v13.x/api/esm.html">13.x</a></li>
311<li><a href="https://nodejs.org/docs/latest-v12.x/api/esm.html">12.x</a></li>
312<li><a href="https://nodejs.org/docs/latest-v11.x/api/esm.html">11.x</a></li>
313<li><a href="https://nodejs.org/docs/latest-v10.x/api/esm.html">10.x</a></li>
314<li><a href="https://nodejs.org/docs/latest-v9.x/api/esm.html">9.x</a></li>
315<li><a href="https://nodejs.org/docs/latest-v8.x/api/esm.html">8.x</a></li></ol></div>
316    </li>
317
318            <li class="picker-header">
319              <a href="#">
320                <span class="collapsed-arrow">&#x25ba;</span><span class="expanded-arrow">&#x25bc;</span>
321                Options
322              </a>
323
324              <div class="picker">
325                <ul>
326                  <li>
327                    <a href="all.html">View on single page</a>
328                  </li>
329                  <li>
330                    <a href="esm.json">View as JSON</a>
331                  </li>
332                  <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/esm.md">Edit on GitHub</a></li>
333                </ul>
334              </div>
335            </li>
336          </ul>
337        </div>
338        <hr>
339      </header>
340
341      <details id="toc" open><summary>Table of contents</summary><ul>
342<li><a href="#modules-ecmascript-modules">Modules: ECMAScript modules</a>
343<ul>
344<li><a href="#introduction">Introduction</a></li>
345<li><a href="#enabling">Enabling</a></li>
346<li><a href="#packages">Packages</a></li>
347<li><a href="#import-specifiers"><code>import</code> Specifiers</a>
348<ul>
349<li><a href="#terminology">Terminology</a></li>
350<li><a href="#mandatory-file-extensions">Mandatory file extensions</a></li>
351<li><a href="#urls">URLs</a>
352<ul>
353<li><a href="#file-urls"><code>file:</code> URLs</a></li>
354<li><a href="#data-imports"><code>data:</code> imports</a></li>
355<li><a href="#node-imports"><code>node:</code> imports</a></li>
356</ul>
357</li>
358</ul>
359</li>
360<li><span class="stability_1"><a href="#import-assertions">Import assertions</a></span></li>
361<li><a href="#builtin-modules">Builtin modules</a></li>
362<li><a href="#import-expressions"><code>import()</code> expressions</a></li>
363<li><a href="#importmeta"><code>import.meta</code></a>
364<ul>
365<li><a href="#importmetaurl"><code>import.meta.url</code></a></li>
366<li><span class="stability_1"><a href="#importmetaresolvespecifier-parent"><code>import.meta.resolve(specifier[, parent])</code></a></span></li>
367</ul>
368</li>
369<li><a href="#interoperability-with-commonjs">Interoperability with CommonJS</a>
370<ul>
371<li><a href="#import-statements"><code>import</code> statements</a></li>
372<li><a href="#require"><code>require</code></a></li>
373<li><a href="#commonjs-namespaces">CommonJS Namespaces</a></li>
374<li><a href="#differences-between-es-modules-and-commonjs">Differences between ES modules and CommonJS</a>
375<ul>
376<li><a href="#no-require-exports-or-moduleexports">No <code>require</code>, <code>exports</code>, or <code>module.exports</code></a></li>
377<li><a href="#no-__filename-or-__dirname">No <code>__filename</code> or <code>__dirname</code></a></li>
378<li><a href="#no-addon-loading">No Addon Loading</a></li>
379<li><a href="#no-requireresolve">No <code>require.resolve</code></a></li>
380<li><a href="#no-node_path">No <code>NODE_PATH</code></a></li>
381<li><a href="#no-requireextensions">No <code>require.extensions</code></a></li>
382<li><a href="#no-requirecache">No <code>require.cache</code></a></li>
383</ul>
384</li>
385</ul>
386</li>
387<li><span class="stability_1"><a href="#json-modules">JSON modules</a></span></li>
388<li><span class="stability_1"><a href="#wasm-modules">Wasm modules</a></span></li>
389<li><a href="#top-level-await">Top-level <code>await</code></a></li>
390<li><span class="stability_1"><a href="#https-and-http-imports">HTTPS and HTTP imports</a></span>
391<ul>
392<li><a href="#imports-are-limited-to-http1">Imports are limited to HTTP/1</a></li>
393<li><a href="#http-is-limited-to-loopback-addresses">HTTP is limited to loopback addresses</a></li>
394<li><a href="#authentication-is-never-sent-to-the-destination-server">Authentication is never sent to the destination server.</a></li>
395<li><a href="#cors-is-never-checked-on-the-destination-server">CORS is never checked on the destination server</a></li>
396<li><a href="#cannot-load-non-network-dependencies">Cannot load non-network dependencies</a></li>
397<li><a href="#network-based-loading-is-not-enabled-by-default">Network-based loading is not enabled by default</a></li>
398</ul>
399</li>
400<li><span class="stability_1"><a href="#loaders">Loaders</a></span>
401<ul>
402<li><a href="#hooks">Hooks</a>
403<ul>
404<li><a href="#resolvespecifier-context-nextresolve"><code>resolve(specifier, context, nextResolve)</code></a></li>
405<li><a href="#loadurl-context-nextload"><code>load(url, context, nextLoad)</code></a></li>
406<li><a href="#globalpreload"><code>globalPreload()</code></a></li>
407</ul>
408</li>
409<li><a href="#examples">Examples</a>
410<ul>
411<li><a href="#https-loader">HTTPS loader</a></li>
412<li><a href="#transpiler-loader">Transpiler loader</a></li>
413<li><a href="#import-map-loader">"import map" loader</a></li>
414</ul>
415</li>
416</ul>
417</li>
418<li><a href="#resolution-and-loading-algorithm">Resolution and loading algorithm</a>
419<ul>
420<li><a href="#features">Features</a></li>
421<li><a href="#resolution-algorithm">Resolution algorithm</a></li>
422<li><a href="#resolution-algorithm-specification">Resolution Algorithm Specification</a></li>
423<li><span class="stability_1"><a href="#customizing-esm-specifier-resolution-algorithm">Customizing ESM specifier resolution algorithm</a></span></li>
424</ul>
425</li>
426</ul>
427</li>
428</ul></details>
429
430      <div id="apicontent">
431        <h2>Modules: ECMAScript modules<span><a class="mark" href="#modules-ecmascript-modules" id="modules-ecmascript-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_modules_ecmascript_modules"></a></h2>
432
433
434<div class="api_metadata">
435<details class="changelog"><summary>History</summary>
436<table>
437<tbody><tr><th>Version</th><th>Changes</th></tr>
438<tr><td>v18.6.0</td>
439<td><p>Add support for chaining loaders.</p></td></tr>
440<tr><td>v17.1.0, v16.14.0</td>
441<td><p>Add support for import assertions.</p></td></tr>
442<tr><td>v17.0.0, v16.12.0</td>
443<td><p>Consolidate loader hooks, removed <code>getFormat</code>, <code>getSource</code>, <code>transformSource</code>, and <code>getGlobalPreloadCode</code> hooks added <code>load</code> and <code>globalPreload</code> hooks allowed returning <code>format</code> from either <code>resolve</code> or <code>load</code> hooks.</p></td></tr>
444<tr><td>v14.8.0</td>
445<td><p>Unflag Top-Level Await.</p></td></tr>
446<tr><td>v15.3.0, v14.17.0, v12.22.0</td>
447<td><p>Stabilize modules implementation.</p></td></tr>
448<tr><td>v14.13.0, v12.20.0</td>
449<td><p>Support for detection of CommonJS named exports.</p></td></tr>
450<tr><td>v14.0.0, v13.14.0, v12.20.0</td>
451<td><p>Remove experimental modules warning.</p></td></tr>
452<tr><td>v13.2.0, v12.17.0</td>
453<td><p>Loading ECMAScript modules no longer requires a command-line flag.</p></td></tr>
454<tr><td>v12.0.0</td>
455<td><p>Add support for ES modules using <code>.js</code> file extension via <code>package.json</code> <code>"type"</code> field.</p></td></tr>
456<tr><td>v8.5.0</td>
457<td><p><span>Added in: v8.5.0</span></p></td></tr>
458</tbody></table>
459</details>
460</div>
461<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p>
462<section><h3>Introduction<span><a class="mark" href="#introduction" id="introduction">#</a></span><a aria-hidden="true" class="legacy" id="esm_introduction"></a></h3>
463
464<p>ECMAScript modules are <a href="https://tc39.github.io/ecma262/#sec-modules">the official standard format</a> to package JavaScript
465code 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
466<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export"><code>export</code></a> statements.</p>
467<p>The following example of an ES module exports a function:</p>
468<pre><code class="language-js"><span class="hljs-comment">// addTwo.mjs</span>
469<span class="hljs-keyword">function</span> <span class="hljs-title function_">addTwo</span>(<span class="hljs-params">num</span>) {
470  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
471}
472
473<span class="hljs-keyword">export</span> { addTwo };</code> <button class="copy-button">copy</button></pre>
474<p>The following example of an ES module imports the function from <code>addTwo.mjs</code>:</p>
475<pre><code class="language-js"><span class="hljs-comment">// app.mjs</span>
476<span class="hljs-keyword">import</span> { addTwo } <span class="hljs-keyword">from</span> <span class="hljs-string">'./addTwo.mjs'</span>;
477
478<span class="hljs-comment">// Prints: 6</span>
479<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">addTwo</span>(<span class="hljs-number">4</span>));</code> <button class="copy-button">copy</button></pre>
480<p>Node.js fully supports ECMAScript modules as they are currently specified and
481provides interoperability between them and its original module format,
482<a href="modules.html">CommonJS</a>.</p>
483<!-- Anchors to make sure old links find a target -->
484<p><i id="esm_package_json_type_field"></i><i id="esm_package_scope_and_file_extensions"></i><i id="esm_input_type_flag"></i></p>
485</section><section><h3>Enabling<span><a class="mark" href="#enabling" id="enabling">#</a></span><a aria-hidden="true" class="legacy" id="esm_enabling"></a></h3>
486
487<p>Node.js has two module systems: <a href="modules.html">CommonJS</a> modules and ECMAScript modules.</p>
488<p>Authors can tell Node.js to use the ECMAScript modules loader
489via the <code>.mjs</code> file extension, the <code>package.json</code> <a href="packages.html#type"><code>"type"</code></a> field, or the
490<a href="cli.html#--input-typetype"><code>--input-type</code></a> flag. Outside of those cases, Node.js will use the CommonJS
491module loader. See <a href="packages.html#determining-module-system">Determining module system</a> for more details.</p>
492<!-- Anchors to make sure old links find a target -->
493<p><i id="esm_package_entry_points"></i><i id="esm_main_entry_point_export"></i><i id="esm_subpath_exports"></i><i id="esm_package_exports_fallbacks"></i><i id="esm_exports_sugar"></i><i id="esm_conditional_exports"></i><i id="esm_nested_conditions"></i><i id="esm_self_referencing_a_package_using_its_name"></i><i id="esm_internal_package_imports"></i><i id="esm_dual_commonjs_es_module_packages"></i><i id="esm_dual_package_hazard"></i><i id="esm_writing_dual_packages_while_avoiding_or_minimizing_hazards"></i><i id="esm_approach_1_use_an_es_module_wrapper"></i><i id="esm_approach_2_isolate_state"></i></p>
494</section><section><h3>Packages<span><a class="mark" href="#packages" id="packages">#</a></span><a aria-hidden="true" class="legacy" id="esm_packages"></a></h3>
495<p>This section was moved to <a href="packages.html">Modules: Packages</a>.</p>
496</section><section><h3><code>import</code> Specifiers<span><a class="mark" href="#import-specifiers" id="import-specifiers">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_specifiers"></a></h3>
497<h4>Terminology<span><a class="mark" href="#terminology" id="terminology">#</a></span><a aria-hidden="true" class="legacy" id="esm_terminology"></a></h4>
498<p>The <em>specifier</em> of an <code>import</code> statement is the string after the <code>from</code> keyword,
499e.g. <code>'node:path'</code> in <code>import { sep } from 'node:path'</code>. Specifiers are also
500used in <code>export from</code> statements, and as the argument to an <code>import()</code>
501expression.</p>
502<p>There are three types of specifiers:</p>
503<ul>
504<li>
505<p><em>Relative specifiers</em> like <code>'./startup.js'</code> or <code>'../config.mjs'</code>. They refer
506to a path relative to the location of the importing file. <em>The file extension
507is always necessary for these.</em></p>
508</li>
509<li>
510<p><em>Bare specifiers</em> like <code>'some-package'</code> or <code>'some-package/shuffle'</code>. They can
511refer to the main entry point of a package by the package name, or a
512specific feature module within a package prefixed by the package name as per
513the examples respectively. <em>Including the file extension is only necessary
514for packages without an <a href="packages.html#exports"><code>"exports"</code></a> field.</em></p>
515</li>
516<li>
517<p><em>Absolute specifiers</em> like <code>'file:///opt/nodejs/config.js'</code>. They refer
518directly and explicitly to a full path.</p>
519</li>
520</ul>
521<p>Bare specifier resolutions are handled by the <a href="#resolution-algorithm-specification">Node.js module
522resolution and loading algorithm</a>.
523All other specifier resolutions are always only resolved with
524the standard relative <a href="https://url.spec.whatwg.org/">URL</a> resolution semantics.</p>
525<p>Like in CommonJS, module files within packages can be accessed by appending a
526path to the package name unless the package's <a href="packages.html#nodejs-packagejson-field-definitions"><code>package.json</code></a> contains an
527<a href="packages.html#exports"><code>"exports"</code></a> field, in which case files within packages can only be accessed
528via the paths defined in <a href="packages.html#exports"><code>"exports"</code></a>.</p>
529<p>For details on these package resolution rules that apply to bare specifiers in
530the Node.js module resolution, see the <a href="packages.html">packages documentation</a>.</p>
531<h4>Mandatory file extensions<span><a class="mark" href="#mandatory-file-extensions" id="mandatory-file-extensions">#</a></span><a aria-hidden="true" class="legacy" id="esm_mandatory_file_extensions"></a></h4>
532<p>A file extension must be provided when using the <code>import</code> keyword to resolve
533relative or absolute specifiers. Directory indexes (e.g. <code>'./startup/index.js'</code>)
534must also be fully specified.</p>
535<p>This behavior matches how <code>import</code> behaves in browser environments, assuming a
536typically configured server.</p>
537<h4>URLs<span><a class="mark" href="#urls" id="urls">#</a></span><a aria-hidden="true" class="legacy" id="esm_urls"></a></h4>
538<p>ES modules are resolved and cached as URLs. This means that special characters
539must be <a href="url.html#percent-encoding-in-urls">percent-encoded</a>, such as <code>#</code> with <code>%23</code> and <code>?</code> with <code>%3F</code>.</p>
540<p><code>file:</code>, <code>node:</code>, and <code>data:</code> URL schemes are supported. A specifier like
541<code>'https://example.com/app.js'</code> is not supported natively in Node.js unless using
542a <a href="#https-loader">custom HTTPS loader</a>.</p>
543<h5><code>file:</code> URLs<span><a class="mark" href="#file-urls" id="file-urls">#</a></span><a aria-hidden="true" class="legacy" id="esm_file_urls"></a></h5>
544<p>Modules are loaded multiple times if the <code>import</code> specifier used to resolve
545them has a different query or fragment.</p>
546<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'./foo.mjs?query=1'</span>; <span class="hljs-comment">// loads ./foo.mjs with query of "?query=1"</span>
547<span class="hljs-keyword">import</span> <span class="hljs-string">'./foo.mjs?query=2'</span>; <span class="hljs-comment">// loads ./foo.mjs with query of "?query=2"</span></code> <button class="copy-button">copy</button></pre>
548<p>The volume root may be referenced via <code>/</code>, <code>//</code>, or <code>file:///</code>. Given the
549differences between <a href="https://url.spec.whatwg.org/">URL</a> and path resolution (such as percent encoding
550details), it is recommended to use <a href="url.html#urlpathtofileurlpath">url.pathToFileURL</a> when importing a path.</p>
551<h5><code>data:</code> imports<span><a class="mark" href="#data-imports" id="data-imports">#</a></span><a aria-hidden="true" class="legacy" id="esm_data_imports"></a></h5>
552<div class="api_metadata">
553<span>Added in: v12.10.0</span>
554</div>
555<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>
556<ul>
557<li><code>text/javascript</code> for ES modules</li>
558<li><code>application/json</code> for JSON</li>
559<li><code>application/wasm</code> for Wasm</li>
560</ul>
561<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'data:text/javascript,console.log("hello!");'</span>;
562<span class="hljs-keyword">import</span> _ <span class="hljs-keyword">from</span> <span class="hljs-string">'data:application/json,"world!"'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };</code> <button class="copy-button">copy</button></pre>
563<p><code>data:</code> URLs only resolve <a href="#terminology">bare specifiers</a> for builtin modules
564and <a href="#terminology">absolute specifiers</a>. Resolving
565<a href="#terminology">relative specifiers</a> does not work because <code>data:</code> is not a
566<a href="https://url.spec.whatwg.org/#special-scheme">special scheme</a>. For example, attempting to load <code>./foo</code>
567from <code>data:text/javascript,import "./foo";</code> fails to resolve because there
568is no concept of relative resolution for <code>data:</code> URLs.</p>
569<h5><code>node:</code> imports<span><a class="mark" href="#node-imports" id="node-imports">#</a></span><a aria-hidden="true" class="legacy" id="esm_node_imports"></a></h5>
570<div class="api_metadata">
571<details class="changelog"><summary>History</summary>
572<table>
573<tbody><tr><th>Version</th><th>Changes</th></tr>
574<tr><td>v16.0.0, v14.18.0</td>
575<td><p>Added <code>node:</code> import support to <code>require(...)</code>.</p></td></tr>
576<tr><td>v14.13.1, v12.20.0</td>
577<td><p><span>Added in: v14.13.1, v12.20.0</span></p></td></tr>
578</tbody></table>
579</details>
580</div>
581<p><code>node:</code> URLs are supported as an alternative means to load Node.js builtin
582modules. This URL scheme allows for builtin modules to be referenced by valid
583absolute URL strings.</p>
584<pre><code class="language-js"><span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;</code> <button class="copy-button">copy</button></pre>
585</section><section><h3>Import assertions<span><a class="mark" href="#import-assertions" id="import-assertions">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_assertions"></a></h3>
586<div class="api_metadata">
587<span>Added in: v17.1.0, v16.14.0</span>
588</div>
589<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
590<p>The <a href="https://github.com/tc39/proposal-import-assertions">Import Assertions proposal</a> adds an inline syntax for module import
591statements to pass on more information alongside the module specifier.</p>
592<pre><code class="language-js"><span class="hljs-keyword">import</span> fooData <span class="hljs-keyword">from</span> <span class="hljs-string">'./foo.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };
593
594<span class="hljs-keyword">const</span> { <span class="hljs-attr">default</span>: barData } =
595  <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./bar.json'</span>, { <span class="hljs-attr">assert</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> } });</code> <button class="copy-button">copy</button></pre>
596<p>Node.js supports the following <code>type</code> values, for which the assertion is
597mandatory:</p>
598
599
600
601
602
603
604
605
606
607
608
609
610
611<table><thead><tr><th>Assertion <code>type</code></th><th>Needed for</th></tr></thead><tbody><tr><td><code>'json'</code></td><td><a href="#json-modules">JSON modules</a></td></tr></tbody></table>
612</section><section><h3>Builtin modules<span><a class="mark" href="#builtin-modules" id="builtin-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_builtin_modules"></a></h3>
613<p><a href="modules.html#core-modules">Core modules</a> provide named exports of their public API. A
614default export is also provided which is the value of the CommonJS exports.
615The default export can be used for, among other things, modifying the named
616exports. Named exports of builtin modules are updated only by calling
617<a href="module.html#modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a>.</p>
618<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-title class_">EventEmitter</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
619<span class="hljs-keyword">const</span> e = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();</code> <button class="copy-button">copy</button></pre>
620<pre><code class="language-js"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
621<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'./foo.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err, source</span>) =></span> {
622  <span class="hljs-keyword">if</span> (err) {
623    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
624  } <span class="hljs-keyword">else</span> {
625    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(source);
626  }
627});</code> <button class="copy-button">copy</button></pre>
628<pre><code class="language-js"><span class="hljs-keyword">import</span> fs, { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
629<span class="hljs-keyword">import</span> { syncBuiltinESMExports } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
630<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
631
632fs.<span class="hljs-property">readFileSync</span> = <span class="hljs-function">() =></span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello, ESM'</span>);
633<span class="hljs-title function_">syncBuiltinESMExports</span>();
634
635fs.<span class="hljs-property">readFileSync</span> === readFileSync;</code> <button class="copy-button">copy</button></pre>
636</section><section><h3><code>import()</code> expressions<span><a class="mark" href="#import-expressions" id="import-expressions">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_expressions"></a></h3>
637<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import">Dynamic <code>import()</code></a> is supported in both CommonJS and ES modules. In CommonJS
638modules it can be used to load ES modules.</p>
639</section><section><h3><code>import.meta</code><span><a class="mark" href="#importmeta" id="importmeta">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta"></a></h3>
640<ul>
641<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
642</ul>
643<p>The <code>import.meta</code> meta property is an <code>Object</code> that contains the following
644properties.</p>
645<h4><code>import.meta.url</code><span><a class="mark" href="#importmetaurl" id="importmetaurl">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta_url"></a></h4>
646<ul>
647<li><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>
648</ul>
649<p>This is defined exactly the same as it is in browsers providing the URL of the
650current module file.</p>
651<p>This enables useful patterns such as relative file loading:</p>
652<pre><code class="language-js"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
653<span class="hljs-keyword">const</span> buffer = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'./data.proto'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));</code> <button class="copy-button">copy</button></pre>
654<h4><code>import.meta.resolve(specifier[, parent])</code><span><a class="mark" href="#importmetaresolvespecifier-parent" id="importmetaresolvespecifier-parent">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta_resolve_specifier_parent"></a></h4>
655<!--
656added:
657  - v13.9.0
658  - v12.16.2
659changes:
660  - version:
661      - v16.2.0
662      - v14.18.0
663    pr-url: https://github.com/nodejs/node/pull/38587
664    description: Add support for WHATWG `URL` object to `parentURL` parameter.
665-->
666<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
667<p>This feature is only available with the <code>--experimental-import-meta-resolve</code>
668command flag enabled.</p>
669<ul>
670<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The module specifier to resolve relative to <code>parent</code>.</li>
671<li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="url.html#the-whatwg-url-api" class="type">&#x3C;URL></a> The absolute parent module URL to resolve from. If none
672is specified, the value of <code>import.meta.url</code> is used as the default.</li>
673<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
674</ul>
675<p>Provides a module-relative resolution function scoped to each module, returning
676the URL string.</p>
677<!-- eslint-skip -->
678<pre><code class="language-js"><span class="hljs-keyword">const</span> dependencyAsset = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'component-lib/asset.css'</span>);</code> <button class="copy-button">copy</button></pre>
679<p><code>import.meta.resolve</code> also accepts a second argument which is the parent module
680from which to resolve from:</p>
681<!-- eslint-skip -->
682<pre><code class="language-js"><span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'./dep'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);</code> <button class="copy-button">copy</button></pre>
683<p>This function is asynchronous because the ES module resolver in Node.js is
684allowed to be asynchronous.</p>
685</section><section><h3>Interoperability with CommonJS<span><a class="mark" href="#interoperability-with-commonjs" id="interoperability-with-commonjs">#</a></span><a aria-hidden="true" class="legacy" id="esm_interoperability_with_commonjs"></a></h3>
686<h4><code>import</code> statements<span><a class="mark" href="#import-statements" id="import-statements">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_statements"></a></h4>
687<p>An <code>import</code> statement can reference an ES module or a CommonJS module.
688<code>import</code> statements are permitted only in ES modules, but dynamic <a href="#import-expressions"><code>import()</code></a>
689expressions are supported in CommonJS for loading ES modules.</p>
690<p>When importing <a href="#commonjs-namespaces">CommonJS modules</a>, the
691<code>module.exports</code> object is provided as the default export. Named exports may be
692available, provided by static analysis as a convenience for better ecosystem
693compatibility.</p>
694<h4><code>require</code><span><a class="mark" href="#require" id="require">#</a></span><a aria-hidden="true" class="legacy" id="esm_require"></a></h4>
695<p>The CommonJS module <code>require</code> always treats the files it references as CommonJS.</p>
696<p>Using <code>require</code> to load an ES module is not supported because ES modules have
697asynchronous execution. Instead, use <a href="#import-expressions"><code>import()</code></a> to load an ES module
698from a CommonJS module.</p>
699<h4>CommonJS Namespaces<span><a class="mark" href="#commonjs-namespaces" id="commonjs-namespaces">#</a></span><a aria-hidden="true" class="legacy" id="esm_commonjs_namespaces"></a></h4>
700<p>CommonJS modules consist of a <code>module.exports</code> object which can be of any type.</p>
701<p>When importing a CommonJS module, it can be reliably imported using the ES
702module default import or its corresponding sugar syntax:</p>
703<!-- eslint-disable no-duplicate-imports -->
704<pre><code class="language-js"><span class="hljs-keyword">import</span> { <span class="hljs-keyword">default</span> <span class="hljs-keyword">as</span> cjs } <span class="hljs-keyword">from</span> <span class="hljs-string">'cjs'</span>;
705
706<span class="hljs-comment">// The following import statement is "syntax sugar" (equivalent but sweeter)</span>
707<span class="hljs-comment">// for `{ default as cjsSugar }` in the above import statement:</span>
708<span class="hljs-keyword">import</span> cjsSugar <span class="hljs-keyword">from</span> <span class="hljs-string">'cjs'</span>;
709
710<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs);
711<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs === cjsSugar);
712<span class="hljs-comment">// Prints:</span>
713<span class="hljs-comment">//   &#x3C;module.exports></span>
714<span class="hljs-comment">//   true</span></code> <button class="copy-button">copy</button></pre>
715<p>The ECMAScript Module Namespace representation of a CommonJS module is always
716a namespace with a <code>default</code> export key pointing to the CommonJS
717<code>module.exports</code> value.</p>
718<p>This Module Namespace Exotic Object can be directly observed either when using
719<code>import * as m from 'cjs'</code> or a dynamic import:</p>
720<!-- eslint-skip -->
721<pre><code class="language-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> m <span class="hljs-keyword">from</span> <span class="hljs-string">'cjs'</span>;
722<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m);
723<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m === <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'cjs'</span>));
724<span class="hljs-comment">// Prints:</span>
725<span class="hljs-comment">//   [Module] { default: &#x3C;module.exports> }</span>
726<span class="hljs-comment">//   true</span></code> <button class="copy-button">copy</button></pre>
727<p>For better compatibility with existing usage in the JS ecosystem, Node.js
728in addition attempts to determine the CommonJS named exports of every imported
729CommonJS module to provide them as separate ES module exports using a static
730analysis process.</p>
731<p>For example, consider a CommonJS module written:</p>
732<pre><code class="language-js cjs"><span class="hljs-comment">// cjs.cjs</span>
733<span class="hljs-built_in">exports</span>.<span class="hljs-property">name</span> = <span class="hljs-string">'exported'</span>;</code> <button class="copy-button">copy</button></pre>
734<p>The preceding module supports named imports in ES modules:</p>
735<!-- eslint-disable no-duplicate-imports -->
736<pre><code class="language-js"><span class="hljs-keyword">import</span> { name } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cjs.cjs'</span>;
737<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name);
738<span class="hljs-comment">// Prints: 'exported'</span>
739
740<span class="hljs-keyword">import</span> cjs <span class="hljs-keyword">from</span> <span class="hljs-string">'./cjs.cjs'</span>;
741<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs);
742<span class="hljs-comment">// Prints: { name: 'exported' }</span>
743
744<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> m <span class="hljs-keyword">from</span> <span class="hljs-string">'./cjs.cjs'</span>;
745<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m);
746<span class="hljs-comment">// Prints: [Module] { default: { name: 'exported' }, name: 'exported' }</span></code> <button class="copy-button">copy</button></pre>
747<p>As can be seen from the last example of the Module Namespace Exotic Object being
748logged, the <code>name</code> export is copied off of the <code>module.exports</code> object and set
749directly on the ES module namespace when the module is imported.</p>
750<p>Live binding updates or new exports added to <code>module.exports</code> are not detected
751for these named exports.</p>
752<p>The detection of named exports is based on common syntax patterns but does not
753always correctly detect named exports. In these cases, using the default
754import form described above can be a better option.</p>
755<p>Named exports detection covers many common export patterns, reexport patterns
756and build tool and transpiler outputs. See <a href="https://github.com/nodejs/cjs-module-lexer/tree/1.2.2">cjs-module-lexer</a> for the exact
757semantics implemented.</p>
758<h4>Differences between ES modules and CommonJS<span><a class="mark" href="#differences-between-es-modules-and-commonjs" id="differences-between-es-modules-and-commonjs">#</a></span><a aria-hidden="true" class="legacy" id="esm_differences_between_es_modules_and_commonjs"></a></h4>
759<h5>No <code>require</code>, <code>exports</code>, or <code>module.exports</code><span><a class="mark" href="#no-require-exports-or-moduleexports" id="no-require-exports-or-moduleexports">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_exports_or_module_exports"></a></h5>
760<p>In most cases, the ES module <code>import</code> can be used to load CommonJS modules.</p>
761<p>If needed, a <code>require</code> function can be constructed within an ES module using
762<a href="module.html#modulecreaterequirefilename"><code>module.createRequire()</code></a>.</p>
763<h5>No <code>__filename</code> or <code>__dirname</code><span><a class="mark" href="#no-__filename-or-__dirname" id="no-__filename-or-__dirname">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_filename_or_dirname"></a></h5>
764<p>These CommonJS variables are not available in ES modules.</p>
765<p><code>__filename</code> and <code>__dirname</code> use cases can be replicated via
766<a href="#importmetaurl"><code>import.meta.url</code></a>.</p>
767<h5>No Addon Loading<span><a class="mark" href="#no-addon-loading" id="no-addon-loading">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_addon_loading"></a></h5>
768<p><a href="addons.html">Addons</a> are not currently supported with ES module imports.</p>
769<p>They can instead be loaded with <a href="module.html#modulecreaterequirefilename"><code>module.createRequire()</code></a> or
770<a href="process.html#processdlopenmodule-filename-flags"><code>process.dlopen</code></a>.</p>
771<h5>No <code>require.resolve</code><span><a class="mark" href="#no-requireresolve" id="no-requireresolve">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_resolve"></a></h5>
772<p>Relative resolution can be handled via <code>new URL('./local', import.meta.url)</code>.</p>
773<p>For a complete <code>require.resolve</code> replacement, there is a flagged experimental
774<a href="#importmetaresolvespecifier-parent"><code>import.meta.resolve</code></a> API.</p>
775<p>Alternatively <code>module.createRequire()</code> can be used.</p>
776<h5>No <code>NODE_PATH</code><span><a class="mark" href="#no-node_path" id="no-node_path">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_node_path"></a></h5>
777<p><code>NODE_PATH</code> is not part of resolving <code>import</code> specifiers. Please use symlinks
778if this behavior is desired.</p>
779<h5>No <code>require.extensions</code><span><a class="mark" href="#no-requireextensions" id="no-requireextensions">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_extensions"></a></h5>
780<p><code>require.extensions</code> is not used by <code>import</code>. The expectation is that loader
781hooks can provide this workflow in the future.</p>
782<h5>No <code>require.cache</code><span><a class="mark" href="#no-requirecache" id="no-requirecache">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_cache"></a></h5>
783<p><code>require.cache</code> is not used by <code>import</code> as the ES module loader has its own
784separate cache.</p>
785<p><i id="esm_experimental_json_modules"></i></p>
786</section><section><h3>JSON modules<span><a class="mark" href="#json-modules" id="json-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_json_modules"></a></h3>
787<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
788<p>JSON files can be referenced by <code>import</code>:</p>
789<pre><code class="language-js"><span class="hljs-keyword">import</span> packageConfig <span class="hljs-keyword">from</span> <span class="hljs-string">'./package.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };</code> <button class="copy-button">copy</button></pre>
790<p>The <code>assert { type: 'json' }</code> syntax is mandatory; see <a href="#import-assertions">Import Assertions</a>.</p>
791<p>The imported JSON only exposes a <code>default</code> export. There is no support for named
792exports. A cache entry is created in the CommonJS cache to avoid duplication.
793The same object is returned in CommonJS if the JSON module has already been
794imported from the same path.</p>
795<p><i id="esm_experimental_wasm_modules"></i></p>
796</section><section><h3>Wasm modules<span><a class="mark" href="#wasm-modules" id="wasm-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_wasm_modules"></a></h3>
797<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
798<p>Importing WebAssembly modules is supported under the
799<code>--experimental-wasm-modules</code> flag, allowing any <code>.wasm</code> files to be
800imported as normal modules while also supporting their module imports.</p>
801<p>This integration is in line with the
802<a href="https://github.com/webassembly/esm-integration">ES Module Integration Proposal for WebAssembly</a>.</p>
803<p>For example, an <code>index.mjs</code> containing:</p>
804<pre><code class="language-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> M <span class="hljs-keyword">from</span> <span class="hljs-string">'./module.wasm'</span>;
805<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(M);</code> <button class="copy-button">copy</button></pre>
806<p>executed under:</p>
807<pre><code class="language-bash">node --experimental-wasm-modules index.mjs</code> <button class="copy-button">copy</button></pre>
808<p>would provide the exports interface for the instantiation of <code>module.wasm</code>.</p>
809<p><i id="esm_experimental_top_level_await"></i></p>
810</section><section><h3>Top-level <code>await</code><span><a class="mark" href="#top-level-await" id="top-level-await">#</a></span><a aria-hidden="true" class="legacy" id="esm_top_level_await"></a></h3>
811<div class="api_metadata">
812<span>Added in: v14.8.0</span>
813</div>
814<p>The <code>await</code> keyword may be used in the top level body of an ECMAScript module.</p>
815<p>Assuming an <code>a.mjs</code> with</p>
816<pre><code class="language-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> five = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">5</span>);</code> <button class="copy-button">copy</button></pre>
817<p>And a <code>b.mjs</code> with</p>
818<pre><code class="language-js"><span class="hljs-keyword">import</span> { five } <span class="hljs-keyword">from</span> <span class="hljs-string">'./a.mjs'</span>;
819
820<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(five); <span class="hljs-comment">// Logs `5`</span></code> <button class="copy-button">copy</button></pre>
821<pre><code class="language-bash">node b.mjs <span class="hljs-comment"># works</span></code> <button class="copy-button">copy</button></pre>
822<p>If a top level <code>await</code> expression never resolves, the <code>node</code> process will exit
823with a <code>13</code> <a href="process.html#exit-codes">status code</a>.</p>
824<pre><code class="language-js"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
825<span class="hljs-keyword">import</span> { execPath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
826
827<span class="hljs-title function_">spawn</span>(execPath, [
828  <span class="hljs-string">'--input-type=module'</span>,
829  <span class="hljs-string">'--eval'</span>,
830  <span class="hljs-comment">// Never-resolving Promise:</span>
831  <span class="hljs-string">'await new Promise(() => {})'</span>,
832]).<span class="hljs-title function_">once</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
833  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(code); <span class="hljs-comment">// Logs `13`</span>
834});</code> <button class="copy-button">copy</button></pre>
835</section><section><h3>HTTPS and HTTP imports<span><a class="mark" href="#https-and-http-imports" id="https-and-http-imports">#</a></span><a aria-hidden="true" class="legacy" id="esm_https_and_http_imports"></a></h3>
836<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
837<p>Importing network based modules using <code>https:</code> and <code>http:</code> is supported under
838the <code>--experimental-network-imports</code> flag. This allows web browser-like imports
839to work in Node.js with a few differences due to application stability and
840security concerns that are different when running in a privileged environment
841instead of a browser sandbox.</p>
842<h4>Imports are limited to HTTP/1<span><a class="mark" href="#imports-are-limited-to-http1" id="imports-are-limited-to-http1">#</a></span><a aria-hidden="true" class="legacy" id="esm_imports_are_limited_to_http_1"></a></h4>
843<p>Automatic protocol negotiation for HTTP/2 and HTTP/3 is not yet supported.</p>
844<h4>HTTP is limited to loopback addresses<span><a class="mark" href="#http-is-limited-to-loopback-addresses" id="http-is-limited-to-loopback-addresses">#</a></span><a aria-hidden="true" class="legacy" id="esm_http_is_limited_to_loopback_addresses"></a></h4>
845<p><code>http:</code> is vulnerable to man-in-the-middle attacks and is not allowed to be
846used for addresses outside of the IPv4 address <code>127.0.0.0/8</code> (<code>127.0.0.1</code> to
847<code>127.255.255.255</code>) and the IPv6 address <code>::1</code>. Support for <code>http:</code> is intended
848to be used for local development.</p>
849<h4>Authentication is never sent to the destination server.<span><a class="mark" href="#authentication-is-never-sent-to-the-destination-server" id="authentication-is-never-sent-to-the-destination-server">#</a></span><a aria-hidden="true" class="legacy" id="esm_authentication_is_never_sent_to_the_destination_server"></a></h4>
850<p><code>Authorization</code>, <code>Cookie</code>, and <code>Proxy-Authorization</code> headers are not sent to the
851server. Avoid including user info in parts of imported URLs. A security model
852for safely using these on the server is being worked on.</p>
853<h4>CORS is never checked on the destination server<span><a class="mark" href="#cors-is-never-checked-on-the-destination-server" id="cors-is-never-checked-on-the-destination-server">#</a></span><a aria-hidden="true" class="legacy" id="esm_cors_is_never_checked_on_the_destination_server"></a></h4>
854<p>CORS is designed to allow a server to limit the consumers of an API to a
855specific set of hosts. This is not supported as it does not make sense for a
856server-based implementation.</p>
857<h4>Cannot load non-network dependencies<span><a class="mark" href="#cannot-load-non-network-dependencies" id="cannot-load-non-network-dependencies">#</a></span><a aria-hidden="true" class="legacy" id="esm_cannot_load_non_network_dependencies"></a></h4>
858<p>These modules cannot access other modules that are not over <code>http:</code> or <code>https:</code>.
859To still access local modules while avoiding the security concern, pass in
860references to the local dependencies:</p>
861<pre><code class="language-js mjs"><span class="hljs-comment">// file.mjs</span>
862<span class="hljs-keyword">import</span> worker_threads <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
863<span class="hljs-keyword">import</span> { configure, resize } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://example.com/imagelib.mjs'</span>;
864<span class="hljs-title function_">configure</span>({ worker_threads });</code> <button class="copy-button">copy</button></pre>
865<pre><code class="language-js mjs"><span class="hljs-comment">// https://example.com/imagelib.mjs</span>
866<span class="hljs-keyword">let</span> worker_threads;
867<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">configure</span>(<span class="hljs-params">opts</span>) {
868  worker_threads = opts.<span class="hljs-property">worker_threads</span>;
869}
870<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resize</span>(<span class="hljs-params">img, size</span>) {
871  <span class="hljs-comment">// Perform resizing in worker_thread to avoid main thread blocking</span>
872}</code> <button class="copy-button">copy</button></pre>
873<h4>Network-based loading is not enabled by default<span><a class="mark" href="#network-based-loading-is-not-enabled-by-default" id="network-based-loading-is-not-enabled-by-default">#</a></span><a aria-hidden="true" class="legacy" id="esm_network_based_loading_is_not_enabled_by_default"></a></h4>
874<p>For now, the <code>--experimental-network-imports</code> flag is required to enable loading
875resources over <code>http:</code> or <code>https:</code>. In the future, a different mechanism will be
876used to enforce this. Opt-in is required to prevent transitive dependencies
877inadvertently using potentially mutable state that could affect reliability
878of Node.js applications.</p>
879<p><i id="esm_experimental_loaders"></i></p>
880</section><section><h3>Loaders<span><a class="mark" href="#loaders" id="loaders">#</a></span><a aria-hidden="true" class="legacy" id="esm_loaders"></a></h3>
881<div class="api_metadata">
882<details class="changelog"><summary>History</summary>
883<table>
884<tbody><tr><th>Version</th><th>Changes</th></tr>
885<tr><td>v18.6.0</td>
886<td><p>Add support for chaining loaders.</p></td></tr>
887<tr><td>v16.12.0</td>
888<td><p>Removed <code>getFormat</code>, <code>getSource</code>, <code>transformSource</code>, and <code>globalPreload</code>; added <code>load</code> hook and <code>getGlobalPreload</code> hook.</p></td></tr>
889<tr><td>v8.8.0</td>
890<td><p><span>Added in: v8.8.0</span></p></td></tr>
891</tbody></table>
892</details>
893</div>
894<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
895<blockquote>
896<p>This API is currently being redesigned and will still change.</p>
897</blockquote>
898
899<p>To customize the default module resolution, loader hooks can optionally be
900provided via a <code>--experimental-loader ./loader-name.mjs</code> argument to Node.js.</p>
901<p>When hooks are used they apply to the entry point and all <code>import</code> calls. They
902won't apply to <code>require</code> calls; those still follow <a href="modules.html">CommonJS</a> rules.</p>
903<p>Loaders follow the pattern of <code>--require</code>:</p>
904<pre><code class="language-console">node \
905  --experimental-loader unpkg \
906  --experimental-loader http-to-https \
907  --experimental-loader cache-buster</code> <button class="copy-button">copy</button></pre>
908<p>These are called in the following sequence: <code>cache-buster</code> calls
909<code>http-to-https</code> which calls <code>unpkg</code>.</p>
910<h4>Hooks<span><a class="mark" href="#hooks" id="hooks">#</a></span><a aria-hidden="true" class="legacy" id="esm_hooks"></a></h4>
911<p>Hooks are part of a chain, even if that chain consists of only one custom
912(user-provided) hook and the default hook, which is always present. Hook
913functions nest: each one must always return a plain object, and chaining happens
914as a result of each function calling <code>next&#x3C;hookName>()</code>, which is a reference
915to the subsequent loader’s hook.</p>
916<p>A hook that returns a value lacking a required property triggers an exception.
917A hook that returns without calling <code>next&#x3C;hookName>()</code> <em>and</em> without returning
918<code>shortCircuit: true</code> also triggers an exception. These errors are to help
919prevent unintentional breaks in the chain.</p>
920<h5><code>resolve(specifier, context, nextResolve)</code><span><a class="mark" href="#resolvespecifier-context-nextresolve" id="resolvespecifier-context-nextresolve">#</a></span><a aria-hidden="true" class="legacy" id="esm_resolve_specifier_context_nextresolve"></a></h5>
921<div class="api_metadata">
922<details class="changelog"><summary>History</summary>
923<table>
924<tbody><tr><th>Version</th><th>Changes</th></tr>
925<tr><td>v18.6.0</td>
926<td><p>Add support for chaining resolve hooks. Each hook must either call <code>nextResolve()</code> or include a <code>shortCircuit</code> property set to <code>true</code> in its return.</p></td></tr>
927<tr><td>v17.1.0, v16.14.0</td>
928<td><p>Add support for import assertions.</p></td></tr>
929</tbody></table>
930</details>
931</div>
932<blockquote>
933<p>The loaders API is being redesigned. This hook may disappear or its
934signature may change. Do not rely on the API described below.</p>
935</blockquote>
936<ul>
937<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
938<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
939<ul>
940<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Export conditions of the relevant <code>package.json</code></li>
941<li><code>importAssertions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
942<li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The module importing this one, or undefined
943if this is the Node.js entry point</li>
944</ul>
945</li>
946<li><code>nextResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The subsequent <code>resolve</code> hook in the chain, or the
947Node.js default <code>resolve</code> hook after the last user-supplied <code>resolve</code> hook
948<ul>
949<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
950<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
951</ul>
952</li>
953<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
954<ul>
955<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> A hint to the load hook (it might be
956ignored)
957<code>'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'</code></li>
958<li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A signal that this hook intends to
959terminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li>
960<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 URL to which this input resolves</li>
961</ul>
962</li>
963</ul>
964<p>The <code>resolve</code> hook chain is responsible for resolving file URL for a given
965module specifier and parent URL, and optionally its format (such as <code>'module'</code>)
966as a hint to the <code>load</code> hook. If a format is specified, the <code>load</code> hook is
967ultimately responsible for providing the final <code>format</code> value (and it is free to
968ignore the hint provided by <code>resolve</code>); if <code>resolve</code> provides a <code>format</code>, a
969custom <code>load</code> hook is required even if only to pass the value to the Node.js
970default <code>load</code> hook.</p>
971<p>The module specifier is the string in an <code>import</code> statement or
972<code>import()</code> expression.</p>
973<p>The parent URL is the URL of the module that imported this one, or <code>undefined</code>
974if this is the main entry point for the application.</p>
975<p>The <code>conditions</code> property in <code>context</code> is an array of conditions for
976<a href="packages.html#conditional-exports">package exports conditions</a> that apply to this resolution
977request. They can be used for looking up conditional mappings elsewhere or to
978modify the list when calling the default resolution logic.</p>
979<p>The current <a href="packages.html#conditional-exports">package exports conditions</a> are always in
980the <code>context.conditions</code> array passed into the hook. To guarantee <em>default
981Node.js module specifier resolution behavior</em> when calling <code>defaultResolve</code>, the
982<code>context.conditions</code> array passed to it <em>must</em> include <em>all</em> elements of the
983<code>context.conditions</code> array originally passed into the <code>resolve</code> hook.</p>
984<pre><code class="language-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
985  <span class="hljs-keyword">const</span> { parentURL = <span class="hljs-literal">null</span> } = context;
986
987  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Some condition.</span>
988    <span class="hljs-comment">// For some or all specifiers, do some custom logic for resolving.</span>
989    <span class="hljs-comment">// Always return an object of the form {url: &#x3C;string>}.</span>
990    <span class="hljs-keyword">return</span> {
991      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
992      <span class="hljs-attr">url</span>: parentURL ?
993        <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier, parentURL).<span class="hljs-property">href</span> :
994        <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier).<span class="hljs-property">href</span>,
995    };
996  }
997
998  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() &#x3C; <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Another condition.</span>
999    <span class="hljs-comment">// When calling `defaultResolve`, the arguments can be modified. In this</span>
1000    <span class="hljs-comment">// case it's adding another value for matching conditional exports.</span>
1001    <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, {
1002      ...context,
1003      <span class="hljs-attr">conditions</span>: [...context.<span class="hljs-property">conditions</span>, <span class="hljs-string">'another-condition'</span>],
1004    });
1005  }
1006
1007  <span class="hljs-comment">// Defer to the next hook in the chain, which would be the</span>
1008  <span class="hljs-comment">// Node.js default resolve if this is the last user-specified loader.</span>
1009  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier);
1010}</code> <button class="copy-button">copy</button></pre>
1011<h5><code>load(url, context, nextLoad)</code><span><a class="mark" href="#loadurl-context-nextload" id="loadurl-context-nextload">#</a></span><a aria-hidden="true" class="legacy" id="esm_load_url_context_nextload"></a></h5>
1012<div class="api_metadata">
1013<details class="changelog"><summary>History</summary>
1014<table>
1015<tbody><tr><th>Version</th><th>Changes</th></tr>
1016<tr><td>v18.6.0</td>
1017<td><p>Add support for chaining load hooks. Each hook must either call <code>nextLoad()</code> or include a <code>shortCircuit</code> property set to <code>true</code> in its return.</p></td></tr>
1018</tbody></table>
1019</details>
1020</div>
1021<blockquote>
1022<p>The loaders API is being redesigned. This hook may disappear or its
1023signature may change. Do not rely on the API described below.</p>
1024</blockquote>
1025<blockquote>
1026<p>In a previous version of this API, this was split across 3 separate, now
1027deprecated, hooks (<code>getFormat</code>, <code>getSource</code>, and <code>transformSource</code>).</p>
1028</blockquote>
1029<ul>
1030<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 URL returned by the <code>resolve</code> chain</li>
1031<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
1032<ul>
1033<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Export conditions of the relevant <code>package.json</code></li>
1034<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The format optionally supplied by the
1035<code>resolve</code> hook chain</li>
1036<li><code>importAssertions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1037</ul>
1038</li>
1039<li><code>nextLoad</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The subsequent <code>load</code> hook in the chain, or the
1040Node.js default <code>load</code> hook after the last user-supplied <code>load</code> hook
1041<ul>
1042<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1043<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
1044</ul>
1045</li>
1046<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
1047<ul>
1048<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
1049<li><code>shortCircuit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A signal that this hook intends to
1050terminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li>
1051<li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> The source for Node.js to evaluate</li>
1052</ul>
1053</li>
1054</ul>
1055<p>The <code>load</code> hook provides a way to define a custom method of determining how
1056a URL should be interpreted, retrieved, and parsed. It is also in charge of
1057validating the import assertion.</p>
1058<p>The final value of <code>format</code> must be one of the following:</p>
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094<table><thead><tr><th><code>format</code></th><th>Description</th><th>Acceptable types for <code>source</code> returned by <code>load</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>'json'</code></td><td>Load a JSON file</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> }</td></tr><tr><td><code>'module'</code></td><td>Load an ES module</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> }</td></tr><tr><td><code>'wasm'</code></td><td>Load a WebAssembly module</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> }</td></tr></tbody></table>
1095<p>The value of <code>source</code> is ignored for type <code>'builtin'</code> because currently it is
1096not possible to replace the value of a Node.js builtin (core) module. The value
1097of <code>source</code> is ignored for type <code>'commonjs'</code> because the CommonJS module loader
1098does not provide a mechanism for the ES module loader to override the
1099<a href="#commonjs-namespaces">CommonJS module return value</a>. This limitation might be
1100overcome in the future.</p>
1101<blockquote>
1102<p><strong>Caveat</strong>: The ESM <code>load</code> hook and namespaced exports from CommonJS modules
1103are incompatible. Attempting to use them together will result in an empty
1104object from the import. This may be addressed in the future.</p>
1105</blockquote>
1106<blockquote>
1107<p>These types all correspond to classes defined in ECMAScript.</p>
1108</blockquote>
1109<ul>
1110<li>The specific <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> object is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a>.</li>
1111<li>The specific <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> object is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>.</li>
1112</ul>
1113<p>If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>)
1114is not a string, it is converted to a string using <a href="util.html#class-utiltextdecoder"><code>util.TextDecoder</code></a>.</p>
1115<p>The <code>load</code> hook provides a way to define a custom method for retrieving the
1116source code of an ES module specifier. This would allow a loader to potentially
1117avoid reading files from disk. It could also be used to map an unrecognized
1118format to a supported one, for example <code>yaml</code> to <code>module</code>.</p>
1119<pre><code class="language-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
1120  <span class="hljs-keyword">const</span> { format } = context;
1121
1122  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Some condition</span>
1123    <span class="hljs-comment">/*
1124      For some or all URLs, do some custom logic for retrieving the source.
1125      Always return an object of the form {
1126        format: &#x3C;string>,
1127        source: &#x3C;string|buffer>,
1128      }.
1129    */</span>
1130    <span class="hljs-keyword">return</span> {
1131      format,
1132      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
1133      <span class="hljs-attr">source</span>: <span class="hljs-string">'...'</span>,
1134    };
1135  }
1136
1137  <span class="hljs-comment">// Defer to the next hook in the chain.</span>
1138  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
1139}</code> <button class="copy-button">copy</button></pre>
1140<p>In a more advanced scenario, this can also be used to transform an unsupported
1141source to a supported one (see <a href="#examples">Examples</a> below).</p>
1142<h5><code>globalPreload()</code><span><a class="mark" href="#globalpreload" id="globalpreload">#</a></span><a aria-hidden="true" class="legacy" id="esm_globalpreload"></a></h5>
1143<div class="api_metadata">
1144<details class="changelog"><summary>History</summary>
1145<table>
1146<tbody><tr><th>Version</th><th>Changes</th></tr>
1147<tr><td>v18.6.0</td>
1148<td><p>Add support for chaining globalPreload hooks.</p></td></tr>
1149</tbody></table>
1150</details>
1151</div>
1152<blockquote>
1153<p>The loaders API is being redesigned. This hook may disappear or its
1154signature may change. Do not rely on the API described below.</p>
1155</blockquote>
1156<blockquote>
1157<p>In a previous version of this API, this hook was named
1158<code>getGlobalPreloadCode</code>.</p>
1159</blockquote>
1160<ul>
1161<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Information to assist the preload code
1162<ul>
1163<li><code>port</code> <a href="worker_threads.html#class-messageport" class="type">&#x3C;MessagePort></a></li>
1164</ul>
1165</li>
1166<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Code to run before application startup</li>
1167</ul>
1168<p>Sometimes it might be necessary to run some code inside of the same global
1169scope that the application runs in. This hook allows the return of a string
1170that is run as a sloppy-mode script on startup.</p>
1171<p>Similar to how CommonJS wrappers work, the code runs in an implicit function
1172scope. The only argument is a <code>require</code>-like function that can be used to load
1173builtins like "fs": <code>getBuiltin(request: string)</code>.</p>
1174<p>If the code needs more advanced <code>require</code> features, it has to construct
1175its own <code>require</code> using  <code>module.createRequire()</code>.</p>
1176<pre><code class="language-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">globalPreload</span>(<span class="hljs-params">context</span>) {
1177  <span class="hljs-keyword">return</span> <span class="hljs-string">`\
1178globalThis.someInjectedProperty = 42;
1179console.log('I just set some globals!');
1180
1181const { createRequire } = getBuiltin('module');
1182const { cwd } = getBuiltin('process');
1183
1184const require = createRequire(cwd() + '/&#x3C;preload>');
1185// [...]
1186`</span>;
1187}</code> <button class="copy-button">copy</button></pre>
1188<p>In order to allow communication between the application and the loader, another
1189argument is provided to the preload code: <code>port</code>. This is available as a
1190parameter to the loader hook and inside of the source text returned by the hook.
1191Some care must be taken in order to properly call <a href="https://nodejs.org/dist/latest-v17.x/docs/api/worker_threads.html#portref"><code>port.ref()</code></a> and
1192<a href="https://nodejs.org/dist/latest-v17.x/docs/api/worker_threads.html#portunref"><code>port.unref()</code></a> to prevent a process from being in a state where it won't
1193close normally.</p>
1194<pre><code class="language-js"><span class="hljs-comment">/**
1195 * This example has the application context send a message to the loader
1196 * and sends the message back to the application context
1197 */</span>
1198<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">globalPreload</span>(<span class="hljs-params">{ port }</span>) {
1199  port.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">evt</span>) =></span> {
1200    port.<span class="hljs-title function_">postMessage</span>(evt.<span class="hljs-property">data</span>);
1201  };
1202  <span class="hljs-keyword">return</span> <span class="hljs-string">`\
1203    port.postMessage('console.log("I went to the Loader and back");');
1204    port.onmessage = (evt) => {
1205      eval(evt.data);
1206    };
1207  `</span>;
1208}</code> <button class="copy-button">copy</button></pre>
1209<h4>Examples<span><a class="mark" href="#examples" id="examples">#</a></span><a aria-hidden="true" class="legacy" id="esm_examples"></a></h4>
1210<p>The various loader hooks can be used together to accomplish wide-ranging
1211customizations of the Node.js code loading and evaluation behaviors.</p>
1212<h5>HTTPS loader<span><a class="mark" href="#https-loader" id="https-loader">#</a></span><a aria-hidden="true" class="legacy" id="esm_https_loader"></a></h5>
1213<p>In current Node.js, specifiers starting with <code>https://</code> are experimental (see
1214<a href="#https-and-http-imports">HTTPS and HTTP imports</a>).</p>
1215<p>The loader below registers hooks to enable rudimentary support for such
1216specifiers. While this may seem like a significant improvement to Node.js core
1217functionality, there are substantial downsides to actually using this loader:
1218performance is much slower than loading files from disk, there is no caching,
1219and there is no security.</p>
1220<pre><code class="language-js"><span class="hljs-comment">// https-loader.mjs</span>
1221<span class="hljs-keyword">import</span> { get } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
1222
1223<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
1224  <span class="hljs-comment">// For JavaScript to be loaded over the network, we need to fetch and</span>
1225  <span class="hljs-comment">// return it.</span>
1226  <span class="hljs-keyword">if</span> (url.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'https://'</span>)) {
1227    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
1228      <span class="hljs-title function_">get</span>(url, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
1229        <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
1230        res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
1231        res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> data += chunk);
1232        res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">resolve</span>({
1233          <span class="hljs-comment">// This example assumes all network-provided JavaScript is ES module</span>
1234          <span class="hljs-comment">// code.</span>
1235          <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span>,
1236          <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
1237          <span class="hljs-attr">source</span>: data,
1238        }));
1239      }).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-title function_">reject</span>(err));
1240    });
1241  }
1242
1243  <span class="hljs-comment">// Let Node.js handle all other URLs.</span>
1244  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
1245}</code> <button class="copy-button">copy</button></pre>
1246<pre><code class="language-js"><span class="hljs-comment">// main.mjs</span>
1247<span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">VERSION</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://coffeescript.org/browser-compiler-modern/coffeescript.js'</span>;
1248
1249<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable constant_">VERSION</span>);</code> <button class="copy-button">copy</button></pre>
1250<p>With the preceding loader, running
1251<code>node --experimental-loader ./https-loader.mjs ./main.mjs</code>
1252prints the current version of CoffeeScript per the module at the URL in
1253<code>main.mjs</code>.</p>
1254<h5>Transpiler loader<span><a class="mark" href="#transpiler-loader" id="transpiler-loader">#</a></span><a aria-hidden="true" class="legacy" id="esm_transpiler_loader"></a></h5>
1255<p>Sources that are in formats Node.js doesn't understand can be converted into
1256JavaScript using the <a href="#loadurl-context-nextload"><code>load</code> hook</a>.</p>
1257<p>This is less performant than transpiling source files before running
1258Node.js; a transpiler loader should only be used for development and testing
1259purposes.</p>
1260<pre><code class="language-js"><span class="hljs-comment">// coffeescript-loader.mjs</span>
1261<span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
1262<span class="hljs-keyword">import</span> { dirname, extname, resolve <span class="hljs-keyword">as</span> resolvePath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
1263<span class="hljs-keyword">import</span> { cwd } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
1264<span class="hljs-keyword">import</span> { fileURLToPath, pathToFileURL } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
1265<span class="hljs-keyword">import</span> <span class="hljs-title class_">CoffeeScript</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'coffeescript'</span>;
1266
1267<span class="hljs-keyword">const</span> baseURL = <span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-string">`<span class="hljs-subst">${cwd()}</span>/`</span>).<span class="hljs-property">href</span>;
1268
1269<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
1270  <span class="hljs-keyword">if</span> (extensionsRegex.<span class="hljs-title function_">test</span>(url)) {
1271    <span class="hljs-comment">// Now that we patched resolve to let CoffeeScript URLs through, we need to</span>
1272    <span class="hljs-comment">// tell Node.js what format such URLs should be interpreted as. Because</span>
1273    <span class="hljs-comment">// CoffeeScript transpiles into JavaScript, it should be one of the two</span>
1274    <span class="hljs-comment">// JavaScript formats: 'commonjs' or 'module'.</span>
1275
1276    <span class="hljs-comment">// CoffeeScript files can be either CommonJS or ES modules, so we want any</span>
1277    <span class="hljs-comment">// CoffeeScript file to be treated by Node.js the same as a .js file at the</span>
1278    <span class="hljs-comment">// same location. To determine how Node.js would interpret an arbitrary .js</span>
1279    <span class="hljs-comment">// file, search up the file system for the nearest parent package.json file</span>
1280    <span class="hljs-comment">// and read its "type" field.</span>
1281    <span class="hljs-keyword">const</span> format = <span class="hljs-keyword">await</span> <span class="hljs-title function_">getPackageType</span>(url);
1282    <span class="hljs-comment">// When a hook returns a format of 'commonjs', `source` is ignored.</span>
1283    <span class="hljs-comment">// To handle CommonJS files, a handler needs to be registered with</span>
1284    <span class="hljs-comment">// `require.extensions` in order to process the files with the CommonJS</span>
1285    <span class="hljs-comment">// loader. Avoiding the need for a separate CommonJS handler is a future</span>
1286    <span class="hljs-comment">// enhancement planned for ES module loaders.</span>
1287    <span class="hljs-keyword">if</span> (format === <span class="hljs-string">'commonjs'</span>) {
1288      <span class="hljs-keyword">return</span> {
1289        format,
1290        <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
1291      };
1292    }
1293
1294    <span class="hljs-keyword">const</span> { <span class="hljs-attr">source</span>: rawSource } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">nextLoad</span>(url, { ...context, format });
1295    <span class="hljs-comment">// This hook converts CoffeeScript source code into JavaScript source code</span>
1296    <span class="hljs-comment">// for all imported CoffeeScript files.</span>
1297    <span class="hljs-keyword">const</span> transformedSource = <span class="hljs-title function_">coffeeCompile</span>(rawSource.<span class="hljs-title function_">toString</span>(), url);
1298
1299    <span class="hljs-keyword">return</span> {
1300      format,
1301      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
1302      <span class="hljs-attr">source</span>: transformedSource,
1303    };
1304  }
1305
1306  <span class="hljs-comment">// Let Node.js handle all other URLs.</span>
1307  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
1308}
1309
1310<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getPackageType</span>(<span class="hljs-params">url</span>) {
1311  <span class="hljs-comment">// `url` is only a file path during the first iteration when passed the</span>
1312  <span class="hljs-comment">// resolved url from the load() hook</span>
1313  <span class="hljs-comment">// an actual file path from load() will contain a file extension as it's</span>
1314  <span class="hljs-comment">// required by the spec</span>
1315  <span class="hljs-comment">// this simple truthy check for whether `url` contains a file extension will</span>
1316  <span class="hljs-comment">// work for most projects but does not cover some edge-cases (such as</span>
1317  <span class="hljs-comment">// extensionless files or a url ending in a trailing space)</span>
1318  <span class="hljs-keyword">const</span> isFilePath = !!<span class="hljs-title function_">extname</span>(url);
1319  <span class="hljs-comment">// If it is a file path, get the directory it's in</span>
1320  <span class="hljs-keyword">const</span> dir = isFilePath ?
1321    <span class="hljs-title function_">dirname</span>(<span class="hljs-title function_">fileURLToPath</span>(url)) :
1322    url;
1323  <span class="hljs-comment">// Compose a file path to a package.json in the same directory,</span>
1324  <span class="hljs-comment">// which may or may not exist</span>
1325  <span class="hljs-keyword">const</span> packagePath = <span class="hljs-title function_">resolvePath</span>(dir, <span class="hljs-string">'package.json'</span>);
1326  <span class="hljs-comment">// Try to read the possibly nonexistent package.json</span>
1327  <span class="hljs-keyword">const</span> type = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(packagePath, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span> })
1328    .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">filestring</span>) =></span> <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(filestring).<span class="hljs-property">type</span>)
1329    .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
1330      <span class="hljs-keyword">if</span> (err?.<span class="hljs-property">code</span> !== <span class="hljs-string">'ENOENT'</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
1331    });
1332  <span class="hljs-comment">// Ff package.json existed and contained a `type` field with a value, voila</span>
1333  <span class="hljs-keyword">if</span> (type) <span class="hljs-keyword">return</span> type;
1334  <span class="hljs-comment">// Otherwise, (if not at the root) continue checking the next directory up</span>
1335  <span class="hljs-comment">// If at the root, stop and return false</span>
1336  <span class="hljs-keyword">return</span> dir.<span class="hljs-property">length</span> > <span class="hljs-number">1</span> &#x26;&#x26; <span class="hljs-title function_">getPackageType</span>(<span class="hljs-title function_">resolvePath</span>(dir, <span class="hljs-string">'..'</span>));
1337}</code> <button class="copy-button">copy</button></pre>
1338<pre><code class="language-coffee"><span class="hljs-comment"># main.coffee</span>
1339<span class="hljs-keyword">import</span> { scream } <span class="hljs-keyword">from</span> <span class="hljs-string">'./scream.coffee'</span>
1340console.log scream <span class="hljs-string">'hello, world'</span>
1341
1342<span class="hljs-keyword">import</span> { version } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>
1343console.log <span class="hljs-string">"Brought to you by Node.js version <span class="hljs-subst">#{version}</span>"</span></code> <button class="copy-button">copy</button></pre>
1344<pre><code class="language-coffee"><span class="hljs-comment"># scream.coffee</span>
1345<span class="hljs-keyword">export</span> scream = <span class="hljs-function"><span class="hljs-params">(str)</span> -></span> str.toUpperCase()</code> <button class="copy-button">copy</button></pre>
1346<p>With the preceding loader, running
1347<code>node --experimental-loader ./coffeescript-loader.mjs main.coffee</code>
1348causes <code>main.coffee</code> to be turned into JavaScript after its source code is
1349loaded from disk but before Node.js executes it; and so on for any <code>.coffee</code>,
1350<code>.litcoffee</code> or <code>.coffee.md</code> files referenced via <code>import</code> statements of any
1351loaded file.</p>
1352<h5>"import map" loader<span><a class="mark" href="#import-map-loader" id="import-map-loader">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_map_loader"></a></h5>
1353<p>The previous two loaders defined <code>load</code> hooks. This is an example of a loader
1354that does its work via the <code>resolve</code> hook. This loader reads an
1355<code>import-map.json</code> file that specifies which specifiers to override to another
1356URL (this is a very simplistic implemenation of a small subset of the
1357"import maps" specification).</p>
1358<pre><code class="language-js"><span class="hljs-comment">// import-map-loader.js</span>
1359<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
1360
1361<span class="hljs-keyword">const</span> { imports } = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-keyword">await</span> fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'import-map.json'</span>));
1362
1363<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
1364  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">hasOwn</span>(imports, specifier)) {
1365    <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(imports[specifier], context);
1366  }
1367
1368  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, context);
1369}</code> <button class="copy-button">copy</button></pre>
1370<p>Let's assume we have these files:</p>
1371<pre><code class="language-js"><span class="hljs-comment">// main.js</span>
1372<span class="hljs-keyword">import</span> <span class="hljs-string">'a-module'</span>;</code> <button class="copy-button">copy</button></pre>
1373<pre><code class="language-json"><span class="hljs-comment">// import-map.json</span>
1374<span class="hljs-punctuation">{</span>
1375  <span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
1376    <span class="hljs-attr">"a-module"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./some-module.js"</span>
1377  <span class="hljs-punctuation">}</span>
1378<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
1379<pre><code class="language-js"><span class="hljs-comment">// some-module.js</span>
1380<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'some module!'</span>);</code> <button class="copy-button">copy</button></pre>
1381<p>If you run <code>node --experimental-loader ./import-map-loader.js main.js</code>
1382the output will be <code>some module!</code>.</p>
1383</section><section><h3>Resolution and loading algorithm<span><a class="mark" href="#resolution-and-loading-algorithm" id="resolution-and-loading-algorithm">#</a></span><a aria-hidden="true" class="legacy" id="esm_resolution_and_loading_algorithm"></a></h3>
1384<h4>Features<span><a class="mark" href="#features" id="features">#</a></span><a aria-hidden="true" class="legacy" id="esm_features"></a></h4>
1385<p>The default resolver has the following properties:</p>
1386<ul>
1387<li>FileURL-based resolution as is used by ES modules</li>
1388<li>Relative and absolute URL resolution</li>
1389<li>No default extensions</li>
1390<li>No folder mains</li>
1391<li>Bare specifier package resolution lookup through node_modules</li>
1392<li>Does not fail on unknown extensions or protocols</li>
1393<li>Can optionally provide a hint of the format to the loading phase</li>
1394</ul>
1395<p>The default loader has the following properties</p>
1396<ul>
1397<li>Support for builtin module loading via <code>node:</code> URLs</li>
1398<li>Support for "inline" module loading via <code>data:</code> URLs</li>
1399<li>Support for <code>file:</code> module loading</li>
1400<li>Fails on any other URL protocol</li>
1401<li>Fails on unknown extensions for <code>file:</code> loading
1402(supports only <code>.cjs</code>, <code>.js</code>, and <code>.mjs</code>)</li>
1403</ul>
1404<h4>Resolution algorithm<span><a class="mark" href="#resolution-algorithm" id="resolution-algorithm">#</a></span><a aria-hidden="true" class="legacy" id="esm_resolution_algorithm"></a></h4>
1405<p>The algorithm to load an ES module specifier is given through the
1406<strong>ESM_RESOLVE</strong> method below. It returns the resolved URL for a
1407module specifier relative to a parentURL.</p>
1408<p>The resolution algorithm determines the full resolved URL for a module
1409load, along with its suggested module format. The resolution algorithm
1410does not determine whether the resolved URL protocol can be loaded,
1411or whether the file extensions are permitted, instead these validations
1412are applied by Node.js during the load phase
1413(for example, if it was asked to load a URL that has a protocol that is
1414not <code>file:</code>, <code>data:</code>, <code>node:</code>, or if <code>--experimental-network-imports</code>
1415is enabled, <code>https:</code>).</p>
1416<p>The algorithm also tries to determine the format of the file based
1417on the extension (see <code>ESM_FILE_FORMAT</code> algorithm below). If it does
1418not recognize the file extension (eg if it is not <code>.mjs</code>, <code>.cjs</code>, or
1419<code>.json</code>), then a format of <code>undefined</code> is returned,
1420which will throw during the load phase.</p>
1421<p>The algorithm to determine the module format of a resolved URL is
1422provided by <strong>ESM_FILE_FORMAT</strong>, which returns the unique module
1423format for any file. The <em>"module"</em> format is returned for an ECMAScript
1424Module, while the <em>"commonjs"</em> format is used to indicate loading through the
1425legacy CommonJS loader. Additional formats such as <em>"addon"</em> can be extended in
1426future updates.</p>
1427<p>In the following algorithms, all subroutine errors are propagated as errors
1428of these top-level routines unless stated otherwise.</p>
1429<p><em>defaultConditions</em> is the conditional environment name array,
1430<code>["node", "import"]</code>.</p>
1431<p>The resolver can throw the following errors:</p>
1432<ul>
1433<li><em>Invalid Module Specifier</em>: Module specifier is an invalid URL, package name
1434or package subpath specifier.</li>
1435<li><em>Invalid Package Configuration</em>: package.json configuration is invalid or
1436contains an invalid configuration.</li>
1437<li><em>Invalid Package Target</em>: Package exports or imports define a target module
1438for the package that is an invalid type or string target.</li>
1439<li><em>Package Path Not Exported</em>: Package exports do not define or permit a target
1440subpath in the package for the given module.</li>
1441<li><em>Package Import Not Defined</em>: Package imports do not define the specifier.</li>
1442<li><em>Module Not Found</em>: The package or module requested does not exist.</li>
1443<li><em>Unsupported Directory Import</em>: The resolved path corresponds to a directory,
1444which is not a supported target for module imports.</li>
1445</ul>
1446<h4>Resolution Algorithm Specification<span><a class="mark" href="#resolution-algorithm-specification" id="resolution-algorithm-specification">#</a></span><a aria-hidden="true" class="legacy" id="esm_resolution_algorithm_specification"></a></h4>
1447<p><strong>ESM_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>)</p>
1448<blockquote>
1449<ol>
1450<li>Let <em>resolved</em> be <strong>undefined</strong>.</li>
1451<li>If <em>specifier</em> is a valid URL, then
1452<ol>
1453<li>Set <em>resolved</em> to the result of parsing and reserializing
1454<em>specifier</em> as a URL.</li>
1455</ol>
1456</li>
1457<li>Otherwise, if <em>specifier</em> starts with <em>"/"</em>, <em>"./"</em>, or <em>"../"</em>, then
1458<ol>
1459<li>Set <em>resolved</em> to the URL resolution of <em>specifier</em> relative to
1460<em>parentURL</em>.</li>
1461</ol>
1462</li>
1463<li>Otherwise, if <em>specifier</em> starts with <em>"#"</em>, then
1464<ol>
1465<li>Set <em>resolved</em> to the result of
1466<strong>PACKAGE_IMPORTS_RESOLVE</strong>(<em>specifier</em>,
1467<em>parentURL</em>, <em>defaultConditions</em>).</li>
1468</ol>
1469</li>
1470<li>Otherwise,
1471<ol>
1472<li>Note: <em>specifier</em> is now a bare specifier.</li>
1473<li>Set <em>resolved</em> the result of
1474<strong>PACKAGE_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>).</li>
1475</ol>
1476</li>
1477<li>Let <em>format</em> be <strong>undefined</strong>.</li>
1478<li>If <em>resolved</em> is a <em>"file:"</em> URL, then
1479<ol>
1480<li>If <em>resolved</em> contains any percent encodings of <em>"/"</em> or <em>"\"</em> (<em>"%2F"</em>
1481and <em>"%5C"</em> respectively), then
1482<ol>
1483<li>Throw an <em>Invalid Module Specifier</em> error.</li>
1484</ol>
1485</li>
1486<li>If the file at <em>resolved</em> is a directory, then
1487<ol>
1488<li>Throw an <em>Unsupported Directory Import</em> error.</li>
1489</ol>
1490</li>
1491<li>If the file at <em>resolved</em> does not exist, then
1492<ol>
1493<li>Throw a <em>Module Not Found</em> error.</li>
1494</ol>
1495</li>
1496<li>Set <em>resolved</em> to the real path of <em>resolved</em>, maintaining the
1497same URL querystring and fragment components.</li>
1498<li>Set <em>format</em> to the result of <strong>ESM_FILE_FORMAT</strong>(<em>resolved</em>).</li>
1499</ol>
1500</li>
1501<li>Otherwise,
1502<ol>
1503<li>Set <em>format</em> the module format of the content type associated with the
1504URL <em>resolved</em>.</li>
1505</ol>
1506</li>
1507<li>Return <em>format</em> and <em>resolved</em> to the loading phase</li>
1508</ol>
1509</blockquote>
1510<p><strong>PACKAGE_RESOLVE</strong>(<em>packageSpecifier</em>, <em>parentURL</em>)</p>
1511<blockquote>
1512<ol>
1513<li>Let <em>packageName</em> be <strong>undefined</strong>.</li>
1514<li>If <em>packageSpecifier</em> is an empty string, then
1515<ol>
1516<li>Throw an <em>Invalid Module Specifier</em> error.</li>
1517</ol>
1518</li>
1519<li>If <em>packageSpecifier</em> is a Node.js builtin module name, then
1520<ol>
1521<li>Return the string <em>"node:"</em> concatenated with <em>packageSpecifier</em>.</li>
1522</ol>
1523</li>
1524<li>If <em>packageSpecifier</em> does not start with <em>"@"</em>, then
1525<ol>
1526<li>Set <em>packageName</em> to the substring of <em>packageSpecifier</em> until the first
1527<em>"/"</em> separator or the end of the string.</li>
1528</ol>
1529</li>
1530<li>Otherwise,
1531<ol>
1532<li>If <em>packageSpecifier</em> does not contain a <em>"/"</em> separator, then
1533<ol>
1534<li>Throw an <em>Invalid Module Specifier</em> error.</li>
1535</ol>
1536</li>
1537<li>Set <em>packageName</em> to the substring of <em>packageSpecifier</em>
1538until the second <em>"/"</em> separator or the end of the string.</li>
1539</ol>
1540</li>
1541<li>If <em>packageName</em> starts with <em>"."</em> or contains <em>"\"</em> or <em>"%"</em>, then
1542<ol>
1543<li>Throw an <em>Invalid Module Specifier</em> error.</li>
1544</ol>
1545</li>
1546<li>Let <em>packageSubpath</em> be <em>"."</em> concatenated with the substring of
1547<em>packageSpecifier</em> from the position at the length of <em>packageName</em>.</li>
1548<li>If <em>packageSubpath</em> ends in <em>"/"</em>, then
1549<ol>
1550<li>Throw an <em>Invalid Module Specifier</em> error.</li>
1551</ol>
1552</li>
1553<li>Let <em>selfUrl</em> be the result of
1554<strong>PACKAGE_SELF_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>).</li>
1555<li>If <em>selfUrl</em> is not <strong>undefined</strong>, return <em>selfUrl</em>.</li>
1556<li>While <em>parentURL</em> is not the file system root,
1557<ol>
1558<li>Let <em>packageURL</em> be the URL resolution of <em>"node_modules/"</em>
1559concatenated with <em>packageSpecifier</em>, relative to <em>parentURL</em>.</li>
1560<li>Set <em>parentURL</em> to the parent folder URL of <em>parentURL</em>.</li>
1561<li>If the folder at <em>packageURL</em> does not exist, then
1562<ol>
1563<li>Continue the next loop iteration.</li>
1564</ol>
1565</li>
1566<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
1567<li>If <em>pjson</em> is not <strong>null</strong> and <em>pjson</em>.<em>exports</em> is not <strong>null</strong> or
1568<strong>undefined</strong>, then
1569<ol>
1570<li>Return the result of <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>,
1571<em>packageSubpath</em>, <em>pjson.exports</em>, <em>defaultConditions</em>).</li>
1572</ol>
1573</li>
1574<li>Otherwise, if <em>packageSubpath</em> is equal to <em>"."</em>, then
1575<ol>
1576<li>If <em>pjson.main</em> is a string, then
1577<ol>
1578<li>Return the URL resolution of <em>main</em> in <em>packageURL</em>.</li>
1579</ol>
1580</li>
1581</ol>
1582</li>
1583<li>Otherwise,
1584<ol>
1585<li>Return the URL resolution of <em>packageSubpath</em> in <em>packageURL</em>.</li>
1586</ol>
1587</li>
1588</ol>
1589</li>
1590<li>Throw a <em>Module Not Found</em> error.</li>
1591</ol>
1592</blockquote>
1593<p><strong>PACKAGE_SELF_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>)</p>
1594<blockquote>
1595<ol>
1596<li>Let <em>packageURL</em> be the result of <strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li>
1597<li>If <em>packageURL</em> is <strong>null</strong>, then
1598<ol>
1599<li>Return <strong>undefined</strong>.</li>
1600</ol>
1601</li>
1602<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
1603<li>If <em>pjson</em> is <strong>null</strong> or if <em>pjson</em>.<em>exports</em> is <strong>null</strong> or
1604<strong>undefined</strong>, then
1605<ol>
1606<li>Return <strong>undefined</strong>.</li>
1607</ol>
1608</li>
1609<li>If <em>pjson.name</em> is equal to <em>packageName</em>, then
1610<ol>
1611<li>Return the result of <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>,
1612<em>packageSubpath</em>, <em>pjson.exports</em>, <em>defaultConditions</em>).</li>
1613</ol>
1614</li>
1615<li>Otherwise, return <strong>undefined</strong>.</li>
1616</ol>
1617</blockquote>
1618<p><strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>subpath</em>, <em>exports</em>, <em>conditions</em>)</p>
1619<blockquote>
1620<ol>
1621<li>If <em>exports</em> is an Object with both a key starting with <em>"."</em> and a key not
1622starting with <em>"."</em>, throw an <em>Invalid Package Configuration</em> error.</li>
1623<li>If <em>subpath</em> is equal to <em>"."</em>, then
1624<ol>
1625<li>Let <em>mainExport</em> be <strong>undefined</strong>.</li>
1626<li>If <em>exports</em> is a String or Array, or an Object containing no keys
1627starting with <em>"."</em>, then
1628<ol>
1629<li>Set <em>mainExport</em> to <em>exports</em>.</li>
1630</ol>
1631</li>
1632<li>Otherwise if <em>exports</em> is an Object containing a <em>"."</em> property, then
1633<ol>
1634<li>Set <em>mainExport</em> to <em>exports</em>[<em>"."</em>].</li>
1635</ol>
1636</li>
1637<li>If <em>mainExport</em> is not <strong>undefined</strong>, then
1638<ol>
1639<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(
1640<em>packageURL</em>, <em>mainExport</em>, <strong>null</strong>, <strong>false</strong>, <em>conditions</em>).</li>
1641<li>If <em>resolved</em> is not <strong>null</strong> or <strong>undefined</strong>, return <em>resolved</em>.</li>
1642</ol>
1643</li>
1644</ol>
1645</li>
1646<li>Otherwise, if <em>exports</em> is an Object and all keys of <em>exports</em> start with
1647<em>"."</em>, then
1648<ol>
1649<li>Let <em>matchKey</em> be the string <em>"./"</em> concatenated with <em>subpath</em>.</li>
1650<li>Let <em>resolved</em> be the result of <strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(
1651<em>matchKey</em>, <em>exports</em>, <em>packageURL</em>, <strong>false</strong>, <em>conditions</em>).</li>
1652<li>If <em>resolved</em> is not <strong>null</strong> or <strong>undefined</strong>, return <em>resolved</em>.</li>
1653</ol>
1654</li>
1655<li>Throw a <em>Package Path Not Exported</em> error.</li>
1656</ol>
1657</blockquote>
1658<p><strong>PACKAGE_IMPORTS_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>, <em>conditions</em>)</p>
1659<blockquote>
1660<ol>
1661<li>Assert: <em>specifier</em> begins with <em>"#"</em>.</li>
1662<li>If <em>specifier</em> is exactly equal to <em>"#"</em> or starts with <em>"#/"</em>, then
1663<ol>
1664<li>Throw an <em>Invalid Module Specifier</em> error.</li>
1665</ol>
1666</li>
1667<li>Let <em>packageURL</em> be the result of <strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li>
1668<li>If <em>packageURL</em> is not <strong>null</strong>, then
1669<ol>
1670<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
1671<li>If <em>pjson.imports</em> is a non-null Object, then
1672<ol>
1673<li>Let <em>resolved</em> be the result of
1674<strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(
1675<em>specifier</em>, <em>pjson.imports</em>, <em>packageURL</em>, <strong>true</strong>, <em>conditions</em>).</li>
1676<li>If <em>resolved</em> is not <strong>null</strong> or <strong>undefined</strong>, return <em>resolved</em>.</li>
1677</ol>
1678</li>
1679</ol>
1680</li>
1681<li>Throw a <em>Package Import Not Defined</em> error.</li>
1682</ol>
1683</blockquote>
1684<p><strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(<em>matchKey</em>, <em>matchObj</em>, <em>packageURL</em>,
1685<em>isImports</em>, <em>conditions</em>)</p>
1686<blockquote>
1687<ol>
1688<li>If <em>matchKey</em> is a key of <em>matchObj</em> and does not contain <em>"*"</em>, then
1689<ol>
1690<li>Let <em>target</em> be the value of <em>matchObj</em>[<em>matchKey</em>].</li>
1691<li>Return the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(<em>packageURL</em>,
1692<em>target</em>, <strong>null</strong>, <em>isImports</em>, <em>conditions</em>).</li>
1693</ol>
1694</li>
1695<li>Let <em>expansionKeys</em> be the list of keys of <em>matchObj</em> containing only a
1696single <em>"*"</em>, sorted by the sorting function <strong>PATTERN_KEY_COMPARE</strong>
1697which orders in descending order of specificity.</li>
1698<li>For each key <em>expansionKey</em> in <em>expansionKeys</em>, do
1699<ol>
1700<li>Let <em>patternBase</em> be the substring of <em>expansionKey</em> up to but excluding
1701the first <em>"*"</em> character.</li>
1702<li>If <em>matchKey</em> starts with but is not equal to <em>patternBase</em>, then
1703<ol>
1704<li>Let <em>patternTrailer</em> be the substring of <em>expansionKey</em> from the
1705index after the first <em>"*"</em> character.</li>
1706<li>If <em>patternTrailer</em> has zero length, or if <em>matchKey</em> ends with
1707<em>patternTrailer</em> and the length of <em>matchKey</em> is greater than or
1708equal to the length of <em>expansionKey</em>, then
1709<ol>
1710<li>Let <em>target</em> be the value of <em>matchObj</em>[<em>expansionKey</em>].</li>
1711<li>Let <em>patternMatch</em> be the substring of <em>matchKey</em> starting at the
1712index of the length of <em>patternBase</em> up to the length of
1713<em>matchKey</em> minus the length of <em>patternTrailer</em>.</li>
1714<li>Return the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(<em>packageURL</em>,
1715<em>target</em>, <em>patternMatch</em>, <em>isImports</em>, <em>conditions</em>).</li>
1716</ol>
1717</li>
1718</ol>
1719</li>
1720</ol>
1721</li>
1722<li>Return <strong>null</strong>.</li>
1723</ol>
1724</blockquote>
1725<p><strong>PATTERN_KEY_COMPARE</strong>(<em>keyA</em>, <em>keyB</em>)</p>
1726<blockquote>
1727<ol>
1728<li>Assert: <em>keyA</em> ends with <em>"/"</em> or contains only a single <em>"*"</em>.</li>
1729<li>Assert: <em>keyB</em> ends with <em>"/"</em> or contains only a single <em>"*"</em>.</li>
1730<li>Let <em>baseLengthA</em> be the index of <em>"*"</em> in <em>keyA</em> plus one, if <em>keyA</em>
1731contains <em>"*"</em>, or the length of <em>keyA</em> otherwise.</li>
1732<li>Let <em>baseLengthB</em> be the index of <em>"*"</em> in <em>keyB</em> plus one, if <em>keyB</em>
1733contains <em>"*"</em>, or the length of <em>keyB</em> otherwise.</li>
1734<li>If <em>baseLengthA</em> is greater than <em>baseLengthB</em>, return -1.</li>
1735<li>If <em>baseLengthB</em> is greater than <em>baseLengthA</em>, return 1.</li>
1736<li>If <em>keyA</em> does not contain <em>"*"</em>, return 1.</li>
1737<li>If <em>keyB</em> does not contain <em>"*"</em>, return -1.</li>
1738<li>If the length of <em>keyA</em> is greater than the length of <em>keyB</em>, return -1.</li>
1739<li>If the length of <em>keyB</em> is greater than the length of <em>keyA</em>, return 1.</li>
1740<li>Return 0.</li>
1741</ol>
1742</blockquote>
1743<p><strong>PACKAGE_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>, <em>patternMatch</em>,
1744<em>isImports</em>, <em>conditions</em>)</p>
1745<blockquote>
1746<ol>
1747<li>If <em>target</em> is a String, then
1748<ol>
1749<li>If <em>target</em> does not start with <em>"./"</em>, then
1750<ol>
1751<li>If <em>isImports</em> is <strong>false</strong>, or if <em>target</em> starts with <em>"../"</em> or
1752<em>"/"</em>, or if <em>target</em> is a valid URL, then
1753<ol>
1754<li>Throw an <em>Invalid Package Target</em> error.</li>
1755</ol>
1756</li>
1757<li>If <em>patternMatch</em> is a String, then
1758<ol>
1759<li>Return <strong>PACKAGE_RESOLVE</strong>(<em>target</em> with every instance of <em>"*"</em>
1760replaced by <em>patternMatch</em>, <em>packageURL</em> + <em>"/"</em>).</li>
1761</ol>
1762</li>
1763<li>Return <strong>PACKAGE_RESOLVE</strong>(<em>target</em>, <em>packageURL</em> + <em>"/"</em>).</li>
1764</ol>
1765</li>
1766<li>If <em>target</em> split on <em>"/"</em> or <em>"\"</em> contains any <em>""</em>, <em>"."</em>, <em>".."</em>,
1767or <em>"node_modules"</em> segments after the first <em>"."</em> segment, case
1768insensitive and including percent encoded variants, throw an <em>Invalid
1769Package Target</em> error.</li>
1770<li>Let <em>resolvedTarget</em> be the URL resolution of the concatenation of
1771<em>packageURL</em> and <em>target</em>.</li>
1772<li>Assert: <em>resolvedTarget</em> is contained in <em>packageURL</em>.</li>
1773<li>If <em>patternMatch</em> is <strong>null</strong>, then
1774<ol>
1775<li>Return <em>resolvedTarget</em>.</li>
1776</ol>
1777</li>
1778<li>If <em>patternMatch</em> split on <em>"/"</em> or <em>"\"</em> contains any <em>""</em>, <em>"."</em>,
1779<em>".."</em>, or <em>"node_modules"</em> segments, case insensitive and including
1780percent encoded variants, throw an <em>Invalid Module Specifier</em> error.</li>
1781<li>Return the URL resolution of <em>resolvedTarget</em> with every instance of
1782<em>"*"</em> replaced with <em>patternMatch</em>.</li>
1783</ol>
1784</li>
1785<li>Otherwise, if <em>target</em> is a non-null Object, then
1786<ol>
1787<li>If <em>exports</em> contains any index property keys, as defined in ECMA-262
1788<a href="https://tc39.es/ecma262/#integer-index">6.1.7 Array Index</a>, throw an <em>Invalid Package Configuration</em> error.</li>
1789<li>For each property <em>p</em> of <em>target</em>, in object insertion order as,
1790<ol>
1791<li>If <em>p</em> equals <em>"default"</em> or <em>conditions</em> contains an entry for <em>p</em>,
1792then
1793<ol>
1794<li>Let <em>targetValue</em> be the value of the <em>p</em> property in <em>target</em>.</li>
1795<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(
1796<em>packageURL</em>, <em>targetValue</em>, <em>patternMatch</em>, <em>isImports</em>,
1797<em>conditions</em>).</li>
1798<li>If <em>resolved</em> is equal to <strong>undefined</strong>, continue the loop.</li>
1799<li>Return <em>resolved</em>.</li>
1800</ol>
1801</li>
1802</ol>
1803</li>
1804<li>Return <strong>undefined</strong>.</li>
1805</ol>
1806</li>
1807<li>Otherwise, if <em>target</em> is an Array, then
1808<ol>
1809<li>If _target.length is zero, return <strong>null</strong>.</li>
1810<li>For each item <em>targetValue</em> in <em>target</em>, do
1811<ol>
1812<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(
1813<em>packageURL</em>, <em>targetValue</em>, <em>patternMatch</em>, <em>isImports</em>,
1814<em>conditions</em>), continuing the loop on any <em>Invalid Package Target</em>
1815error.</li>
1816<li>If <em>resolved</em> is <strong>undefined</strong>, continue the loop.</li>
1817<li>Return <em>resolved</em>.</li>
1818</ol>
1819</li>
1820<li>Return or throw the last fallback resolution <strong>null</strong> return or error.</li>
1821</ol>
1822</li>
1823<li>Otherwise, if <em>target</em> is <em>null</em>, return <strong>null</strong>.</li>
1824<li>Otherwise throw an <em>Invalid Package Target</em> error.</li>
1825</ol>
1826</blockquote>
1827<p><strong>ESM_FILE_FORMAT</strong>(<em>url</em>)</p>
1828<blockquote>
1829<ol>
1830<li>Assert: <em>url</em> corresponds to an existing file.</li>
1831<li>If <em>url</em> ends in <em>".mjs"</em>, then
1832<ol>
1833<li>Return <em>"module"</em>.</li>
1834</ol>
1835</li>
1836<li>If <em>url</em> ends in <em>".cjs"</em>, then
1837<ol>
1838<li>Return <em>"commonjs"</em>.</li>
1839</ol>
1840</li>
1841<li>If <em>url</em> ends in <em>".json"</em>, then
1842<ol>
1843<li>Return <em>"json"</em>.</li>
1844</ol>
1845</li>
1846<li>Let <em>packageURL</em> be the result of <strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>url</em>).</li>
1847<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
1848<li>If <em>pjson?.type</em> exists and is <em>"module"</em>, then
1849<ol>
1850<li>If <em>url</em> ends in <em>".js"</em>, then
1851<ol>
1852<li>Return <em>"module"</em>.</li>
1853</ol>
1854</li>
1855<li>Return <strong>undefined</strong>.</li>
1856</ol>
1857</li>
1858<li>Otherwise,
1859<ol>
1860<li>Return <strong>undefined</strong>.</li>
1861</ol>
1862</li>
1863</ol>
1864</blockquote>
1865<p><strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>url</em>)</p>
1866<blockquote>
1867<ol>
1868<li>Let <em>scopeURL</em> be <em>url</em>.</li>
1869<li>While <em>scopeURL</em> is not the file system root,
1870<ol>
1871<li>Set <em>scopeURL</em> to the parent URL of <em>scopeURL</em>.</li>
1872<li>If <em>scopeURL</em> ends in a <em>"node_modules"</em> path segment, return <strong>null</strong>.</li>
1873<li>Let <em>pjsonURL</em> be the resolution of <em>"package.json"</em> within
1874<em>scopeURL</em>.</li>
1875<li>if the file at <em>pjsonURL</em> exists, then
1876<ol>
1877<li>Return <em>scopeURL</em>.</li>
1878</ol>
1879</li>
1880</ol>
1881</li>
1882<li>Return <strong>null</strong>.</li>
1883</ol>
1884</blockquote>
1885<p><strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>)</p>
1886<blockquote>
1887<ol>
1888<li>Let <em>pjsonURL</em> be the resolution of <em>"package.json"</em> within <em>packageURL</em>.</li>
1889<li>If the file at <em>pjsonURL</em> does not exist, then
1890<ol>
1891<li>Return <strong>null</strong>.</li>
1892</ol>
1893</li>
1894<li>If the file at <em>packageURL</em> does not parse as valid JSON, then
1895<ol>
1896<li>Throw an <em>Invalid Package Configuration</em> error.</li>
1897</ol>
1898</li>
1899<li>Return the parsed JSON source of the file at <em>pjsonURL</em>.</li>
1900</ol>
1901</blockquote>
1902<h4>Customizing ESM specifier resolution algorithm<span><a class="mark" href="#customizing-esm-specifier-resolution-algorithm" id="customizing-esm-specifier-resolution-algorithm">#</a></span><a aria-hidden="true" class="legacy" id="esm_customizing_esm_specifier_resolution_algorithm"></a></h4>
1903<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p>
1904<blockquote>
1905<p>Do not rely on this flag. We plan to remove it once the
1906<a href="#loaders">Loaders API</a> has advanced to the point that equivalent functionality can
1907be achieved via custom loaders.</p>
1908</blockquote>
1909<p>The current specifier resolution does not support all default behavior of
1910the CommonJS loader. One of the behavior differences is automatic resolution
1911of file extensions and the ability to import directories that have an index
1912file.</p>
1913<p>The <code>--experimental-specifier-resolution=[mode]</code> flag can be used to customize
1914the extension resolution algorithm. The default mode is <code>explicit</code>, which
1915requires the full path to a module be provided to the loader. To enable the
1916automatic extension resolution and importing from directories that include an
1917index file use the <code>node</code> mode.</p>
1918<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node index.mjs</span>
1919success!
1920<span class="hljs-meta prompt_">$ </span><span class="language-bash">node index <span class="hljs-comment"># Failure!</span></span>
1921Error: Cannot find module
1922<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-specifier-resolution=node index</span>
1923success!</code> <button class="copy-button">copy</button></pre>
1924<!-- Note: The cjs-module-lexer link should be kept in-sync with the deps version --></section>
1925        <!-- API END -->
1926      </div>
1927    </div>
1928  </div>
1929</body>
1930</html>
1931