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="v14.21.2"> 7 <title>Modules: ECMAScript modules | Node.js v14.21.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</head> 13<body class="alt apidoc" id="api-section-esm"> 14 <div id="content" class="clearfix"> 15 <div id="column2" class="interior"> 16 <div id="intro" class="interior"> 17 <a href="/" title="Go back to the home page"> 18 Node.js 19 </a> 20 </div> 21 <ul> 22<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> 23<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> 24</ul> 25<hr class="line"> 26<ul> 27<li><a href="assert.html" class="nav-assert">Assertion testing</a></li> 28<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> 29<li><a href="buffer.html" class="nav-buffer">Buffer</a></li> 30<li><a href="addons.html" class="nav-addons">C++ addons</a></li> 31<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> 32<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> 33<li><a href="child_process.html" class="nav-child_process">Child processes</a></li> 34<li><a href="cluster.html" class="nav-cluster">Cluster</a></li> 35<li><a href="cli.html" class="nav-cli">Command-line options</a></li> 36<li><a href="console.html" class="nav-console">Console</a></li> 37<li><a href="corepack.html" class="nav-corepack">Corepack</a></li> 38<li><a href="crypto.html" class="nav-crypto">Crypto</a></li> 39<li><a href="debugger.html" class="nav-debugger">Debugger</a></li> 40<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> 41<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> 42<li><a href="dns.html" class="nav-dns">DNS</a></li> 43<li><a href="domain.html" class="nav-domain">Domain</a></li> 44<li><a href="errors.html" class="nav-errors">Errors</a></li> 45<li><a href="events.html" class="nav-events">Events</a></li> 46<li><a href="fs.html" class="nav-fs">File system</a></li> 47<li><a href="globals.html" class="nav-globals">Globals</a></li> 48<li><a href="http.html" class="nav-http">HTTP</a></li> 49<li><a href="http2.html" class="nav-http2">HTTP/2</a></li> 50<li><a href="https.html" class="nav-https">HTTPS</a></li> 51<li><a href="inspector.html" class="nav-inspector">Inspector</a></li> 52<li><a href="intl.html" class="nav-intl">Internationalization</a></li> 53<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> 54<li><a href="esm.html" class="nav-esm active">Modules: ECMAScript modules</a></li> 55<li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li> 56<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> 57<li><a href="net.html" class="nav-net">Net</a></li> 58<li><a href="os.html" class="nav-os">OS</a></li> 59<li><a href="path.html" class="nav-path">Path</a></li> 60<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> 61<li><a href="policy.html" class="nav-policy">Policies</a></li> 62<li><a href="process.html" class="nav-process">Process</a></li> 63<li><a href="punycode.html" class="nav-punycode">Punycode</a></li> 64<li><a href="querystring.html" class="nav-querystring">Query strings</a></li> 65<li><a href="readline.html" class="nav-readline">Readline</a></li> 66<li><a href="repl.html" class="nav-repl">REPL</a></li> 67<li><a href="report.html" class="nav-report">Report</a></li> 68<li><a href="stream.html" class="nav-stream">Stream</a></li> 69<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> 70<li><a href="timers.html" class="nav-timers">Timers</a></li> 71<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> 72<li><a href="tracing.html" class="nav-tracing">Trace events</a></li> 73<li><a href="tty.html" class="nav-tty">TTY</a></li> 74<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> 75<li><a href="url.html" class="nav-url">URL</a></li> 76<li><a href="util.html" class="nav-util">Utilities</a></li> 77<li><a href="v8.html" class="nav-v8">V8</a></li> 78<li><a href="vm.html" class="nav-vm">VM</a></li> 79<li><a href="wasi.html" class="nav-wasi">WASI</a></li> 80<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> 81<li><a href="zlib.html" class="nav-zlib">Zlib</a></li> 82</ul> 83<hr class="line"> 84<ul> 85<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> 86</ul> 87 </div> 88 89 <div id="column1" data-id="esm" class="interior"> 90 <header> 91 <div class="header-container"> 92 <h1>Node.js v14.21.2 documentation</h1> 93 <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> 94 <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> 95 <path fill="none" d="M0 0h24v24H0z" /> 96 <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"/> 97 <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"/> 98 </svg> 99 <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> 100 <path d="M0 0h24v24H0z" fill="none" /> 101 <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"/> 102 </svg> 103 </button> 104 </div> 105 <div id="gtoc"> 106 <ul> 107 <li> 108 <a href="index.html">Index</a> 109 </li> 110 <li> 111 <a href="all.html">View on single page</a> 112 </li> 113 <li> 114 <a href="esm.json">View as JSON</a> 115 </li> 116 117 <li class="version-picker"> 118 <a href="#">View another version <span>▼</span></a> 119 <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v19.x/api/esm.html">19.x</a></li> 120<li><a href="https://nodejs.org/docs/latest-v18.x/api/esm.html">18.x <b>LTS</b></a></li> 121<li><a href="https://nodejs.org/docs/latest-v17.x/api/esm.html">17.x</a></li> 122<li><a href="https://nodejs.org/docs/latest-v16.x/api/esm.html">16.x <b>LTS</b></a></li> 123<li><a href="https://nodejs.org/docs/latest-v15.x/api/esm.html">15.x</a></li> 124<li><a href="https://nodejs.org/docs/latest-v14.x/api/esm.html">14.x <b>LTS</b></a></li> 125<li><a href="https://nodejs.org/docs/latest-v13.x/api/esm.html">13.x</a></li> 126<li><a href="https://nodejs.org/docs/latest-v12.x/api/esm.html">12.x</a></li> 127<li><a href="https://nodejs.org/docs/latest-v11.x/api/esm.html">11.x</a></li> 128<li><a href="https://nodejs.org/docs/latest-v10.x/api/esm.html">10.x</a></li> 129<li><a href="https://nodejs.org/docs/latest-v9.x/api/esm.html">9.x</a></li> 130<li><a href="https://nodejs.org/docs/latest-v8.x/api/esm.html">8.x</a></li></ol> 131 </li> 132 133 <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/esm.md">Edit on GitHub</a></li> 134 </ul> 135 </div> 136 <hr> 137 </header> 138 139 <details id="toc" open><summary>Table of contents</summary><ul> 140<li><a href="#esm_modules_ecmascript_modules">Modules: ECMAScript modules</a> 141<ul> 142<li><a href="#esm_introduction">Introduction</a></li> 143<li><a href="#esm_enabling">Enabling</a></li> 144<li><a href="#esm_packages">Packages</a></li> 145<li><a href="#esm_import_specifiers"><code>import</code> Specifiers</a> 146<ul> 147<li><a href="#esm_terminology">Terminology</a></li> 148<li><a href="#esm_mandatory_file_extensions">Mandatory file extensions</a></li> 149<li><a href="#esm_urls">URLs</a> 150<ul> 151<li><a href="#esm_file_urls"><code>file:</code> URLs</a></li> 152<li><a href="#esm_data_imports"><code>data:</code> Imports</a></li> 153<li><a href="#esm_node_imports"><code>node:</code> Imports</a></li> 154</ul> 155</li> 156</ul> 157</li> 158<li><a href="#esm_builtin_modules">Builtin modules</a></li> 159<li><a href="#esm_import_expressions"><code>import()</code> expressions</a></li> 160<li><a href="#esm_import_meta"><code>import.meta</code></a> 161<ul> 162<li><a href="#esm_import_meta_url"><code>import.meta.url</code></a></li> 163<li><span class="stability_1"><a href="#esm_import_meta_resolve_specifier_parent"><code>import.meta.resolve(specifier[, parent])</code></a></span></li> 164</ul> 165</li> 166<li><a href="#esm_interoperability_with_commonjs">Interoperability with CommonJS</a> 167<ul> 168<li><a href="#esm_import_statements"><code>import</code> statements</a></li> 169<li><a href="#esm_require"><code>require</code></a></li> 170<li><a href="#esm_commonjs_namespaces">CommonJS Namespaces</a></li> 171<li><a href="#esm_differences_between_es_modules_and_commonjs">Differences between ES modules and CommonJS</a> 172<ul> 173<li><a href="#esm_no_require_exports_or_module_exports">No <code>require</code>, <code>exports</code> or <code>module.exports</code></a></li> 174<li><a href="#esm_no_filename_or_dirname">No <code>__filename</code> or <code>__dirname</code></a></li> 175<li><a href="#esm_no_json_module_loading">No JSON Module Loading</a></li> 176<li><a href="#esm_no_native_module_loading">No Native Module Loading</a></li> 177<li><a href="#esm_no_require_resolve">No <code>require.resolve</code></a></li> 178<li><a href="#esm_no_node_path">No <code>NODE_PATH</code></a></li> 179<li><a href="#esm_no_require_extensions">No <code>require.extensions</code></a></li> 180<li><a href="#esm_no_require_cache">No <code>require.cache</code></a></li> 181</ul> 182</li> 183</ul> 184</li> 185<li><span class="stability_1"><a href="#esm_json_modules">JSON modules</a></span></li> 186<li><span class="stability_1"><a href="#esm_wasm_modules">Wasm modules</a></span></li> 187<li><span class="stability_1"><a href="#esm_top_level_await">Top-level <code>await</code></a></span></li> 188<li><span class="stability_1"><a href="#esm_loaders">Loaders</a></span> 189<ul> 190<li><a href="#esm_hooks">Hooks</a> 191<ul> 192<li><a href="#esm_resolve_specifier_context_defaultresolve"><code>resolve(specifier, context, defaultResolve)</code></a></li> 193<li><a href="#esm_getformat_url_context_defaultgetformat"><code>getFormat(url, context, defaultGetFormat)</code></a></li> 194<li><a href="#esm_getsource_url_context_defaultgetsource"><code>getSource(url, context, defaultGetSource)</code></a></li> 195<li><a href="#esm_transformsource_source_context_defaulttransformsource"><code>transformSource(source, context, defaultTransformSource)</code></a></li> 196<li><a href="#esm_getglobalpreloadcode"><code>getGlobalPreloadCode()</code></a></li> 197</ul> 198</li> 199<li><a href="#esm_examples">Examples</a> 200<ul> 201<li><a href="#esm_https_loader">HTTPS loader</a></li> 202<li><a href="#esm_transpiler_loader">Transpiler loader</a></li> 203</ul> 204</li> 205</ul> 206</li> 207<li><a href="#esm_resolution_algorithm">Resolution algorithm</a> 208<ul> 209<li><a href="#esm_features">Features</a></li> 210<li><a href="#esm_resolver_algorithm">Resolver algorithm</a></li> 211<li><a href="#esm_resolver_algorithm_specification">Resolver Algorithm Specification</a></li> 212<li><span class="stability_1"><a href="#esm_customizing_esm_specifier_resolution_algorithm">Customizing ESM specifier resolution algorithm</a></span></li> 213</ul> 214</li> 215</ul> 216</li> 217</ul></details> 218 219 <div id="apicontent"> 220 <h2>Modules: ECMAScript modules<span><a class="mark" href="#esm_modules_ecmascript_modules" id="esm_modules_ecmascript_modules">#</a></span></h2> 221 222 223<div class="api_metadata"> 224<details class="changelog"><summary>History</summary> 225<table> 226<tbody><tr><th>Version</th><th>Changes</th></tr> 227<tr><td>v14.17.0</td> 228<td><p>Stabilize modules implementation.</p></td></tr> 229<tr><td>v14.13.0</td> 230<td><p>Support for detection of CommonJS named exports.</p></td></tr> 231<tr><td>v14.8.0</td> 232<td><p>Unflag Top-Level Await.</p></td></tr> 233<tr><td>v14.0.0, v13.14.0</td> 234<td><p>Remove experimental modules warning.</p></td></tr> 235<tr><td>v13.2.0, v12.17.0</td> 236<td><p>Loading ECMAScript modules no longer requires a command-line flag.</p></td></tr> 237<tr><td>v12.0.0</td> 238<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> 239<tr><td>v8.5.0</td> 240<td><p><span>Added in: v8.5.0</span></p></td></tr> 241</tbody></table> 242</details> 243</div> 244<p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> 245<section><h3>Introduction<span><a class="mark" href="#esm_introduction" id="esm_introduction">#</a></span></h3> 246 247<p>ECMAScript modules are <a href="https://tc39.github.io/ecma262/#sec-modules">the official standard format</a> to package JavaScript 248code 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 249<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export"><code>export</code></a> statements.</p> 250<p>The following example of an ES module exports a function:</p> 251<pre><code class="language-js"><span class="hljs-comment">// addTwo.mjs</span> 252<span class="hljs-keyword">function</span> <span class="hljs-title function_">addTwo</span>(<span class="hljs-params">num</span>) { 253 <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>; 254} 255 256<span class="hljs-keyword">export</span> { addTwo };</code></pre> 257<p>The following example of an ES module imports the function from <code>addTwo.mjs</code>:</p> 258<pre><code class="language-js"><span class="hljs-comment">// app.mjs</span> 259<span class="hljs-keyword">import</span> { addTwo } <span class="hljs-keyword">from</span> <span class="hljs-string">'./addTwo.mjs'</span>; 260 261<span class="hljs-comment">// Prints: 6</span> 262<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></pre> 263<p>Node.js fully supports ECMAScript modules as they are currently specified and 264provides interoperability between them and its original module format, 265<a href="modules.html">CommonJS</a>.</p> 266<!-- Anchors to make sure old links find a target --> 267<p><i id="esm_package_json_type_field"></i> 268<i id="esm_package_scope_and_file_extensions"></i> 269<i id="esm_input_type_flag"></i></p> 270</section><section><h3>Enabling<span><a class="mark" href="#esm_enabling" id="esm_enabling">#</a></span></h3> 271 272<p>Node.js treats JavaScript code as CommonJS modules by default. 273Authors can tell Node.js to treat JavaScript code as ECMAScript modules 274via the <code>.mjs</code> file extension, the <code>package.json</code> <a href="packages.html#packages_type"><code>"type"</code></a> field, or the 275<code>--input-type</code> flag. See 276<a href="packages.html#packages_determining_module_system">Modules: Packages</a> for more 277details.</p> 278<!-- Anchors to make sure old links find a target --> 279<p><i id="esm_package_entry_points"></i> 280<i id="esm_main_entry_point_export"></i> 281<i id="esm_subpath_exports"></i> 282<i id="esm_package_exports_fallbacks"></i> 283<i id="esm_exports_sugar"></i> 284<i id="esm_conditional_exports"></i> 285<i id="esm_nested_conditions"></i> 286<i id="esm_self_referencing_a_package_using_its_name"></i> 287<i id="esm_internal_package_imports"></i> 288<i id="esm_dual_commonjs_es_module_packages"></i> 289<i id="esm_dual_package_hazard"></i> 290<i id="esm_writing_dual_packages_while_avoiding_or_minimizing_hazards"></i> 291<i id="esm_approach_1_use_an_es_module_wrapper"></i> 292<i id="esm_approach_2_isolate_state"></i></p> 293</section><section><h3>Packages<span><a class="mark" href="#esm_packages" id="esm_packages">#</a></span></h3> 294<p>This section was moved to <a href="packages.html">Modules: Packages</a>.</p> 295</section><section><h3><code>import</code> Specifiers<span><a class="mark" href="#esm_import_specifiers" id="esm_import_specifiers">#</a></span></h3> 296<h4>Terminology<span><a class="mark" href="#esm_terminology" id="esm_terminology">#</a></span></h4> 297<p>The <em>specifier</em> of an <code>import</code> statement is the string after the <code>from</code> keyword, 298e.g. <code>'path'</code> in <code>import { sep } from 'path'</code>. Specifiers are also used in 299<code>export from</code> statements, and as the argument to an <code>import()</code> expression.</p> 300<p>There are three types of specifiers:</p> 301<ul> 302<li> 303<p><em>Relative specifiers</em> like <code>'./startup.js'</code> or <code>'../config.mjs'</code>. They refer 304to a path relative to the location of the importing file. <em>The file extension 305is always necessary for these.</em></p> 306</li> 307<li> 308<p><em>Bare specifiers</em> like <code>'some-package'</code> or <code>'some-package/shuffle'</code>. They can 309refer to the main entry point of a package by the package name, or a 310specific feature module within a package prefixed by the package name as per 311the examples respectively. <em>Including the file extension is only necessary 312for packages without an <a href="packages.html#packages_exports"><code>"exports"</code></a> field.</em></p> 313</li> 314<li> 315<p><em>Absolute specifiers</em> like <code>'file:///opt/nodejs/config.js'</code>. They refer 316directly and explicitly to a full path.</p> 317</li> 318</ul> 319<p>Bare specifier resolutions are handled by the <a href="#esm_resolver_algorithm_specification">Node.js module resolution 320algorithm</a>. All other specifier resolutions are always only resolved with 321the standard relative <a href="https://url.spec.whatwg.org/">URL</a> resolution semantics.</p> 322<p>Like in CommonJS, module files within packages can be accessed by appending a 323path to the package name unless the package’s <a href="packages.html#packages_node_js_package_json_field_definitions"><code>package.json</code></a> contains an 324<a href="packages.html#packages_exports"><code>"exports"</code></a> field, in which case files within packages can only be accessed 325via the paths defined in <a href="packages.html#packages_exports"><code>"exports"</code></a>.</p> 326<p>For details on these package resolution rules that apply to bare specifiers in 327the Node.js module resolution, see the <a href="packages.html">packages documentation</a>.</p> 328<h4>Mandatory file extensions<span><a class="mark" href="#esm_mandatory_file_extensions" id="esm_mandatory_file_extensions">#</a></span></h4> 329<p>A file extension must be provided when using the <code>import</code> keyword to resolve 330relative or absolute specifiers. Directory indexes (e.g. <code>'./startup/index.js'</code>) 331must also be fully specified.</p> 332<p>This behavior matches how <code>import</code> behaves in browser environments, assuming a 333typically configured server.</p> 334<h4>URLs<span><a class="mark" href="#esm_urls" id="esm_urls">#</a></span></h4> 335<p>ES modules are resolved and cached as URLs. This means that files containing 336special characters such as <code>#</code> and <code>?</code> need to be escaped.</p> 337<p><code>file:</code>, <code>node:</code>, and <code>data:</code> URL schemes are supported. A specifier like 338<code>'https://example.com/app.js'</code> is not supported natively in Node.js unless using 339a <a href="#esm_https_loader">custom HTTPS loader</a>.</p> 340<h5><code>file:</code> URLs<span><a class="mark" href="#esm_file_urls" id="esm_file_urls">#</a></span></h5> 341<p>Modules are loaded multiple times if the <code>import</code> specifier used to resolve 342them has a different query or fragment.</p> 343<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> 344<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></pre> 345<p>The volume root may be referenced via <code>/</code>, <code>//</code> or <code>file:///</code>. Given the 346differences between <a href="https://url.spec.whatwg.org/">URL</a> and path resolution (such as percent encoding 347details), it is recommended to use <a href="url.html#url_url_pathtofileurl_path">url.pathToFileURL</a> when importing a path.</p> 348<h5><code>data:</code> Imports<span><a class="mark" href="#esm_data_imports" id="esm_data_imports">#</a></span></h5> 349<div class="api_metadata"> 350<span>Added in: v12.10.0</span> 351</div> 352<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> 353<ul> 354<li><code>text/javascript</code> for ES Modules</li> 355<li><code>application/json</code> for JSON (requires <a href="cli.html#cli_experimental_json_modules"><code>--experimental-json-modules</code></a> flag)</li> 356<li><code>application/wasm</code> for Wasm (requires <a href="cli.html#cli_experimental_wasm_modules"><code>--experimental-wasm-modules</code></a> flag)</li> 357</ul> 358<p><code>data:</code> URLs only resolve <a href="#esm_terminology"><em>Bare specifiers</em></a> for builtin modules 359and <a href="#esm_terminology"><em>Absolute specifiers</em></a>. Resolving 360<a href="#esm_terminology"><em>Relative specifiers</em></a> does not work because <code>data:</code> is not a 361<a href="https://url.spec.whatwg.org/#special-scheme">special scheme</a>. For example, attempting to load <code>./foo</code> 362from <code>data:text/javascript,import "./foo";</code> fails to resolve because there 363is no concept of relative resolution for <code>data:</code> URLs. An example of a <code>data:</code> 364URLs being used is:</p> 365<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'data:text/javascript,console.log("hello!");'</span>; 366<span class="hljs-keyword">import</span> _ <span class="hljs-keyword">from</span> <span class="hljs-string">'data:application/json,"world!"'</span>;</code></pre> 367<h5><code>node:</code> Imports<span><a class="mark" href="#esm_node_imports" id="esm_node_imports">#</a></span></h5> 368<div class="api_metadata"> 369<details class="changelog"><summary>History</summary> 370<table> 371<tbody><tr><th>Version</th><th>Changes</th></tr> 372<tr><td>v14.18.0</td> 373<td><p>Added <code>node:</code> import support to <code>require(...)</code>.</p></td></tr> 374<tr><td>v14.13.1, v12.20.0</td> 375<td><p><span>Added in: v14.13.1, v12.20.0</span></p></td></tr> 376</tbody></table> 377</details> 378</div> 379<p><code>node:</code> URLs are supported as an alternative means to load Node.js builtin 380modules. This URL scheme allows for builtin modules to be referenced by valid 381absolute URL strings.</p> 382<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></pre> 383</section><section><h3>Builtin modules<span><a class="mark" href="#esm_builtin_modules" id="esm_builtin_modules">#</a></span></h3> 384<p><a href="modules.html#modules_core_modules">Core modules</a> provide named exports of their public API. A 385default export is also provided which is the value of the CommonJS exports. 386The default export can be used for, among other things, modifying the named 387exports. Named exports of builtin modules are updated only by calling 388<a href="module.html#module_module_syncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a>.</p> 389<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">'events'</span>; 390<span class="hljs-keyword">const</span> e = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();</code></pre> 391<pre><code class="language-js"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>; 392<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> { 393 <span class="hljs-keyword">if</span> (err) { 394 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err); 395 } <span class="hljs-keyword">else</span> { 396 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(source); 397 } 398});</code></pre> 399<pre><code class="language-js"><span class="hljs-keyword">import</span> fs, { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>; 400<span class="hljs-keyword">import</span> { syncBuiltinESMExports } <span class="hljs-keyword">from</span> <span class="hljs-string">'module'</span>; 401 402fs.<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>); 403<span class="hljs-title function_">syncBuiltinESMExports</span>(); 404 405fs.<span class="hljs-property">readFileSync</span> === readFileSync;</code></pre> 406</section><section><h3><code>import()</code> expressions<span><a class="mark" href="#esm_import_expressions" id="esm_import_expressions">#</a></span></h3> 407<p><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports">Dynamic <code>import()</code></a> is supported in both CommonJS and ES modules. In CommonJS 408modules it can be used to load ES modules.</p> 409</section><section><h3><code>import.meta</code><span><a class="mark" href="#esm_import_meta" id="esm_import_meta">#</a></span></h3> 410<ul> 411<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 412</ul> 413<p>The <code>import.meta</code> meta property is an <code>Object</code> that contains the following 414properties.</p> 415<h4><code>import.meta.url</code><span><a class="mark" href="#esm_import_meta_url" id="esm_import_meta_url">#</a></span></h4> 416<ul> 417<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute <code>file:</code> URL of the module.</li> 418</ul> 419<p>This is defined exactly the same as it is in browsers providing the URL of the 420current module file.</p> 421<p>This enables useful patterns such as relative file loading:</p> 422<pre><code class="language-js"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>; 423<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></pre> 424<h4><code>import.meta.resolve(specifier[, parent])</code><span><a class="mark" href="#esm_import_meta_resolve_specifier_parent" id="esm_import_meta_resolve_specifier_parent">#</a></span></h4> 425<!-- 426added: 427 - v13.9.0 428 - v12.16.2 429changes: 430 - version: v14.18.0 431 pr-url: https://github.com/nodejs/node/pull/38587 432 description: Add support for WHATWG `URL` object to `parentURL` parameter. 433--> 434<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> 435<p>This feature is only available with the <code>--experimental-import-meta-resolve</code> 436command flag enabled.</p> 437<ul> 438<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module specifier to resolve relative to <code>parent</code>.</li> 439<li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute parent module URL to resolve from. If none 440is specified, the value of <code>import.meta.url</code> is used as the default.</li> 441<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> 442</ul> 443<p>Provides a module-relative resolution function scoped to each module, returning 444the URL string.</p> 445<!-- eslint-skip --> 446<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></pre> 447<p><code>import.meta.resolve</code> also accepts a second argument which is the parent module 448from which to resolve from:</p> 449<!-- eslint-skip --> 450<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></pre> 451<p>This function is asynchronous because the ES module resolver in Node.js is 452allowed to be asynchronous.</p> 453</section><section><h3>Interoperability with CommonJS<span><a class="mark" href="#esm_interoperability_with_commonjs" id="esm_interoperability_with_commonjs">#</a></span></h3> 454<h4><code>import</code> statements<span><a class="mark" href="#esm_import_statements" id="esm_import_statements">#</a></span></h4> 455<p>An <code>import</code> statement can reference an ES module or a CommonJS module. 456<code>import</code> statements are permitted only in ES modules, but dynamic <a href="#esm_import_expressions"><code>import()</code></a> 457expressions are supported in CommonJS for loading ES modules.</p> 458<p>When importing <a href="#esm_commonjs_namespaces">CommonJS modules</a>, the 459<code>module.exports</code> object is provided as the default export. Named exports may be 460available, provided by static analysis as a convenience for better ecosystem 461compatibility.</p> 462<h4><code>require</code><span><a class="mark" href="#esm_require" id="esm_require">#</a></span></h4> 463<p>The CommonJS module <code>require</code> always treats the files it references as CommonJS.</p> 464<p>Using <code>require</code> to load an ES module is not supported because ES modules have 465asynchronous execution. Instead, use <a href="#esm_import_expressions"><code>import()</code></a> to load an ES module 466from a CommonJS module.</p> 467<h4>CommonJS Namespaces<span><a class="mark" href="#esm_commonjs_namespaces" id="esm_commonjs_namespaces">#</a></span></h4> 468<p>CommonJS modules consist of a <code>module.exports</code> object which can be of any type.</p> 469<p>When importing a CommonJS module, it can be reliably imported using the ES 470module default import or its corresponding sugar syntax:</p> 471<!-- eslint-disable no-duplicate-imports --> 472<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>; 473 474<span class="hljs-comment">// The following import statement is "syntax sugar" (equivalent but sweeter)</span> 475<span class="hljs-comment">// for `{ default as cjsSugar }` in the above import statement:</span> 476<span class="hljs-keyword">import</span> cjsSugar <span class="hljs-keyword">from</span> <span class="hljs-string">'cjs'</span>; 477 478<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs); 479<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs === cjsSugar); 480<span class="hljs-comment">// Prints:</span> 481<span class="hljs-comment">// <module.exports></span> 482<span class="hljs-comment">// true</span></code></pre> 483<p>The ECMAScript Module Namespace representation of a CommonJS module is always 484a namespace with a <code>default</code> export key pointing to the CommonJS 485<code>module.exports</code> value.</p> 486<p>This Module Namespace Exotic Object can be directly observed either when using 487<code>import * as m from 'cjs'</code> or a dynamic import:</p> 488<!-- eslint-skip --> 489<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>; 490<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m); 491<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m === <span class="hljs-keyword">await</span> <span class="hljs-title function_">import</span>(<span class="hljs-string">'cjs'</span>)); 492<span class="hljs-comment">// Prints:</span> 493<span class="hljs-comment">// [Module] { default: <module.exports> }</span> 494<span class="hljs-comment">// true</span></code></pre> 495<p>For better compatibility with existing usage in the JS ecosystem, Node.js 496in addition attempts to determine the CommonJS named exports of every imported 497CommonJS module to provide them as separate ES module exports using a static 498analysis process.</p> 499<p>For example, consider a CommonJS module written:</p> 500<pre><code class="language-js cjs"><span class="hljs-comment">// cjs.cjs</span> 501<span class="hljs-built_in">exports</span>.<span class="hljs-property">name</span> = <span class="hljs-string">'exported'</span>;</code></pre> 502<p>The preceding module supports named imports in ES modules:</p> 503<!-- eslint-disable no-duplicate-imports --> 504<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>; 505<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name); 506<span class="hljs-comment">// Prints: 'exported'</span> 507 508<span class="hljs-keyword">import</span> cjs <span class="hljs-keyword">from</span> <span class="hljs-string">'./cjs.cjs'</span>; 509<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs); 510<span class="hljs-comment">// Prints: { name: 'exported' }</span> 511 512<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>; 513<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m); 514<span class="hljs-comment">// Prints: [Module] { default: { name: 'exported' }, name: 'exported' }</span></code></pre> 515<p>As can be seen from the last example of the Module Namespace Exotic Object being 516logged, the <code>name</code> export is copied off of the <code>module.exports</code> object and set 517directly on the ES module namespace when the module is imported.</p> 518<p>Live binding updates or new exports added to <code>module.exports</code> are not detected 519for these named exports.</p> 520<p>The detection of named exports is based on common syntax patterns but does not 521always correctly detect named exports. In these cases, using the default 522import form described above can be a better option.</p> 523<p>Named exports detection covers many common export patterns, reexport patterns 524and build tool and transpiler outputs. See <a href="https://github.com/guybedford/cjs-module-lexer/tree/1.2.2">cjs-module-lexer</a> for the exact 525semantics implemented.</p> 526<h4>Differences between ES modules and CommonJS<span><a class="mark" href="#esm_differences_between_es_modules_and_commonjs" id="esm_differences_between_es_modules_and_commonjs">#</a></span></h4> 527<h5>No <code>require</code>, <code>exports</code> or <code>module.exports</code><span><a class="mark" href="#esm_no_require_exports_or_module_exports" id="esm_no_require_exports_or_module_exports">#</a></span></h5> 528<p>In most cases, the ES module <code>import</code> can be used to load CommonJS modules.</p> 529<p>If needed, a <code>require</code> function can be constructed within an ES module using 530<a href="module.html#module_module_createrequire_filename"><code>module.createRequire()</code></a>.</p> 531<h5>No <code>__filename</code> or <code>__dirname</code><span><a class="mark" href="#esm_no_filename_or_dirname" id="esm_no_filename_or_dirname">#</a></span></h5> 532<p>These CommonJS variables are not available in ES modules.</p> 533<p><code>__filename</code> and <code>__dirname</code> use cases can be replicated via 534<a href="#esm_import_meta_url"><code>import.meta.url</code></a>.</p> 535<h5>No JSON Module Loading<span><a class="mark" href="#esm_no_json_module_loading" id="esm_no_json_module_loading">#</a></span></h5> 536<p>JSON imports are still experimental and only supported via the 537<code>--experimental-json-modules</code> flag.</p> 538<p>Local JSON files can be loaded relative to <code>import.meta.url</code> with <code>fs</code> directly:</p> 539<!-- eslint-skip --> 540<pre><code class="language-js"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'fs/promises'</span>; 541<span class="hljs-keyword">const</span> json = <span class="hljs-variable constant_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'./dat.json'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>)));</code></pre> 542<p>Alternatively <code>module.createRequire()</code> can be used.</p> 543<h5>No Native Module Loading<span><a class="mark" href="#esm_no_native_module_loading" id="esm_no_native_module_loading">#</a></span></h5> 544<p>Native modules are not currently supported with ES module imports.</p> 545<p>They can instead be loaded with <a href="module.html#module_module_createrequire_filename"><code>module.createRequire()</code></a> or 546<a href="process.html#process_process_dlopen_module_filename_flags"><code>process.dlopen</code></a>.</p> 547<h5>No <code>require.resolve</code><span><a class="mark" href="#esm_no_require_resolve" id="esm_no_require_resolve">#</a></span></h5> 548<p>Relative resolution can be handled via <code>new URL('./local', import.meta.url)</code>.</p> 549<p>For a complete <code>require.resolve</code> replacement, there is a flagged experimental 550<a href="#esm_import_meta_resolve_specifier_parent"><code>import.meta.resolve</code></a> API.</p> 551<p>Alternatively <code>module.createRequire()</code> can be used.</p> 552<h5>No <code>NODE_PATH</code><span><a class="mark" href="#esm_no_node_path" id="esm_no_node_path">#</a></span></h5> 553<p><code>NODE_PATH</code> is not part of resolving <code>import</code> specifiers. Please use symlinks 554if this behavior is desired.</p> 555<h5>No <code>require.extensions</code><span><a class="mark" href="#esm_no_require_extensions" id="esm_no_require_extensions">#</a></span></h5> 556<p><code>require.extensions</code> is not used by <code>import</code>. The expectation is that loader 557hooks can provide this workflow in the future.</p> 558<h5>No <code>require.cache</code><span><a class="mark" href="#esm_no_require_cache" id="esm_no_require_cache">#</a></span></h5> 559<p><code>require.cache</code> is not used by <code>import</code> as the ES module loader has its own 560separate cache.</p> 561<p><i id="esm_experimental_json_modules"></i></p> 562</section><section><h3>JSON modules<span><a class="mark" href="#esm_json_modules" id="esm_json_modules">#</a></span></h3> 563<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> 564<p>Currently importing JSON modules are only supported in the <code>commonjs</code> mode 565and are loaded using the CJS loader. <a href="https://html.spec.whatwg.org/#creating-a-json-module-script">WHATWG JSON modules specification</a> are 566still being standardized, and are experimentally supported by including the 567additional flag <code>--experimental-json-modules</code> when running Node.js.</p> 568<p>When the <code>--experimental-json-modules</code> flag is included, both the 569<code>commonjs</code> and <code>module</code> mode use the new experimental JSON 570loader. The imported JSON only exposes a <code>default</code>. There is no 571support for named exports. A cache entry is created in the CommonJS 572cache to avoid duplication. The same object is returned in 573CommonJS if the JSON module has already been imported from the 574same path.</p> 575<p>Assuming an <code>index.mjs</code> with</p> 576<!-- eslint-skip --> 577<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>;</code></pre> 578<p>The <code>--experimental-json-modules</code> flag is needed for the module 579to work.</p> 580<pre><code class="language-bash">node index.mjs <span class="hljs-comment"># fails</span> 581node --experimental-json-modules index.mjs <span class="hljs-comment"># works</span></code></pre> 582<p><i id="esm_experimental_wasm_modules"></i></p> 583</section><section><h3>Wasm modules<span><a class="mark" href="#esm_wasm_modules" id="esm_wasm_modules">#</a></span></h3> 584<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> 585<p>Importing Web Assembly modules is supported under the 586<code>--experimental-wasm-modules</code> flag, allowing any <code>.wasm</code> files to be 587imported as normal modules while also supporting their module imports.</p> 588<p>This integration is in line with the 589<a href="https://github.com/webassembly/esm-integration">ES Module Integration Proposal for Web Assembly</a>.</p> 590<p>For example, an <code>index.mjs</code> containing:</p> 591<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>; 592<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(M);</code></pre> 593<p>executed under:</p> 594<pre><code class="language-bash">node --experimental-wasm-modules index.mjs</code></pre> 595<p>would provide the exports interface for the instantiation of <code>module.wasm</code>.</p> 596<p><i id="esm_experimental_top_level_await"></i></p> 597</section><section><h3>Top-level <code>await</code><span><a class="mark" href="#esm_top_level_await" id="esm_top_level_await">#</a></span></h3> 598<div class="api_metadata"> 599<span>Added in: v14.8.0</span> 600</div> 601<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> 602<p>The <code>await</code> keyword may be used in the top level body of an ECMAScript module.</p> 603<p>Assuming an <code>a.mjs</code> with</p> 604<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></pre> 605<p>And a <code>b.mjs</code> with</p> 606<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>; 607 608<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(five); <span class="hljs-comment">// Logs `5`</span></code></pre> 609<pre><code class="language-bash">node b.mjs <span class="hljs-comment"># works</span></code></pre> 610<p>If a top level <code>await</code> expression never resolves, the <code>node</code> process will exit 611with a <code>13</code> <a href="process.html#process_exit_codes">status code</a>.</p> 612<pre><code class="language-js"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'child_process'</span>; 613<span class="hljs-keyword">import</span> { execPath } <span class="hljs-keyword">from</span> <span class="hljs-string">'process'</span>; 614 615<span class="hljs-title function_">spawn</span>(execPath, [ 616 <span class="hljs-string">'--input-type=module'</span>, 617 <span class="hljs-string">'--eval'</span>, 618 <span class="hljs-comment">// Never-resolving Promise:</span> 619 <span class="hljs-string">'await new Promise(() => {})'</span>, 620]).<span class="hljs-title function_">once</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> { 621 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(code); <span class="hljs-comment">// Logs `13`</span> 622});</code></pre> 623<p><i id="esm_experimental_loaders"></i></p> 624</section><section><h3>Loaders<span><a class="mark" href="#esm_loaders" id="esm_loaders">#</a></span></h3> 625<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> 626<p><strong>Note: This API is currently being redesigned and will still change.</strong></p> 627 628<p>To customize the default module resolution, loader hooks can optionally be 629provided via a <code>--experimental-loader ./loader-name.mjs</code> argument to Node.js.</p> 630<p>When hooks are used they only apply to ES module loading and not to any 631CommonJS modules loaded.</p> 632<h4>Hooks<span><a class="mark" href="#esm_hooks" id="esm_hooks">#</a></span></h4> 633<h5><code>resolve(specifier, context, defaultResolve)</code><span><a class="mark" href="#esm_resolve_specifier_context_defaultresolve" id="esm_resolve_specifier_context_defaultresolve">#</a></span></h5> 634<blockquote> 635<p>Note: The loaders API is being redesigned. This hook may disappear or its 636signature may change. Do not rely on the API described below.</p> 637</blockquote> 638<ul> 639<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 640<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 641<ul> 642<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> 643<li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 644</ul> 645</li> 646<li><code>defaultResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> 647<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 648<ul> 649<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 650</ul> 651</li> 652</ul> 653<p>The <code>resolve</code> hook returns the resolved file URL for a given module specifier 654and parent URL. The module specifier is the string in an <code>import</code> statement or 655<code>import()</code> expression, and the parent URL is the URL of the module that imported 656this one, or <code>undefined</code> if this is the main entry point for the application.</p> 657<p>The <code>conditions</code> property on the <code>context</code> is an array of conditions for 658<a href="packages.html#packages_conditional_exports">Conditional exports</a> that apply to this resolution request. They can be used 659for looking up conditional mappings elsewhere or to modify the list when calling 660the default resolution logic.</p> 661<p>The current <a href="packages.html#packages_conditional_exports">package exports conditions</a> are always in 662the <code>context.conditions</code> array passed into the hook. To guarantee <em>default 663Node.js module specifier resolution behavior</em> when calling <code>defaultResolve</code>, the 664<code>context.conditions</code> array passed to it <em>must</em> include <em>all</em> elements of the 665<code>context.conditions</code> array originally passed into the <code>resolve</code> hook.</p> 666<pre><code class="language-js"><span class="hljs-comment">/** 667 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">string</span>} <span class="hljs-variable">specifier</span> 668 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">{ 669 * conditions: !Array<string>, 670 * parentURL: !(string | undefined), 671 * </span>}} context 672 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">Function</span>} <span class="hljs-variable">defaultResolve</span> 673 * <span class="hljs-doctag">@returns</span> {<span class="hljs-type">Promise<{ url: string </span>}>} 674 */</span> 675<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, defaultResolve</span>) { 676 <span class="hljs-keyword">const</span> { parentURL = <span class="hljs-literal">null</span> } = context; 677 <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> 678 <span class="hljs-comment">// For some or all specifiers, do some custom logic for resolving.</span> 679 <span class="hljs-comment">// Always return an object of the form {url: <string>}.</span> 680 <span class="hljs-keyword">return</span> { 681 <span class="hljs-attr">url</span>: parentURL ? 682 <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier, parentURL).<span class="hljs-property">href</span> : 683 <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier).<span class="hljs-property">href</span>, 684 }; 685 } 686 <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">// Another condition.</span> 687 <span class="hljs-comment">// When calling `defaultResolve`, the arguments can be modified. In this</span> 688 <span class="hljs-comment">// case it's adding another value for matching conditional exports.</span> 689 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultResolve</span>(specifier, { 690 ...context, 691 <span class="hljs-attr">conditions</span>: [...context.<span class="hljs-property">conditions</span>, <span class="hljs-string">'another-condition'</span>], 692 }); 693 } 694 <span class="hljs-comment">// Defer to Node.js for all other specifiers.</span> 695 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultResolve</span>(specifier, context, defaultResolve); 696}</code></pre> 697<h5><code>getFormat(url, context, defaultGetFormat)</code><span><a class="mark" href="#esm_getformat_url_context_defaultgetformat" id="esm_getformat_url_context_defaultgetformat">#</a></span></h5> 698<blockquote> 699<p>Note: The loaders API is being redesigned. This hook may disappear or its 700signature may change. Do not rely on the API described below.</p> 701</blockquote> 702<ul> 703<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 704<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> 705<li><code>defaultGetFormat</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> 706<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 707<ul> 708<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 709</ul> 710</li> 711</ul> 712<p>The <code>getFormat</code> hook provides a way to define a custom method of determining how 713a URL should be interpreted. The <code>format</code> returned also affects what the 714acceptable forms of source values are for a module when parsing. This can be one 715of the following:</p> 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751<table><thead><tr><th><code>format</code></th><th>Description</th><th>Acceptable Types For <code>source</code> Returned by <code>getSource</code> or <code>transformSource</code></th></tr></thead><tbody><tr><td><code>'builtin'</code></td><td>Load a Node.js builtin module</td><td>Not applicable</td></tr><tr><td><code>'commonjs'</code></td><td>Load a Node.js CommonJS module</td><td>Not applicable</td></tr><tr><td><code>'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> 752<p>Note: These types all correspond to classes defined in ECMAScript.</p> 753<ul> 754<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> 755<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> 756</ul> 757<p>Note: If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>) is 758not a string, it is converted to a string using <a href="util.html#util_class_util_textdecoder"><code>util.TextDecoder</code></a>.</p> 759<pre><code class="language-js"><span class="hljs-comment">/** 760 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">string</span>} <span class="hljs-variable">url</span> 761 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">Object</span>} context (currently empty) 762 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">Function</span>} <span class="hljs-variable">defaultGetFormat</span> 763 * <span class="hljs-doctag">@returns</span> {<span class="hljs-type">Promise<{ format: string </span>}>} 764 */</span> 765<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getFormat</span>(<span class="hljs-params">url, context, defaultGetFormat</span>) { 766 <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> 767 <span class="hljs-comment">// For some or all URLs, do some custom logic for determining format.</span> 768 <span class="hljs-comment">// Always return an object of the form {format: <string>}, where the</span> 769 <span class="hljs-comment">// format is one of the strings in the preceding table.</span> 770 <span class="hljs-keyword">return</span> { 771 <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span>, 772 }; 773 } 774 <span class="hljs-comment">// Defer to Node.js for all other URLs.</span> 775 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultGetFormat</span>(url, context, defaultGetFormat); 776}</code></pre> 777<h5><code>getSource(url, context, defaultGetSource)</code><span><a class="mark" href="#esm_getsource_url_context_defaultgetsource" id="esm_getsource_url_context_defaultgetsource">#</a></span></h5> 778<blockquote> 779<p>Note: The loaders API is being redesigned. This hook may disappear or its 780signature may change. Do not rely on the API described below.</p> 781</blockquote> 782<ul> 783<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 784<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 785<ul> 786<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 787</ul> 788</li> 789<li><code>defaultGetSource</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> 790<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 791<ul> 792<li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> 793</ul> 794</li> 795</ul> 796<p>The <code>getSource</code> hook provides a way to define a custom method for retrieving 797the source code of an ES module specifier. This would allow a loader to 798potentially avoid reading files from disk.</p> 799<pre><code class="language-js"><span class="hljs-comment">/** 800 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">string</span>} <span class="hljs-variable">url</span> 801 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">{ format: string </span>}} context 802 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">Function</span>} <span class="hljs-variable">defaultGetSource</span> 803 * <span class="hljs-doctag">@returns</span> {<span class="hljs-type">Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) </span>}>} 804 */</span> 805<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getSource</span>(<span class="hljs-params">url, context, defaultGetSource</span>) { 806 <span class="hljs-keyword">const</span> { format } = context; 807 <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> 808 <span class="hljs-comment">// For some or all URLs, do some custom logic for retrieving the source.</span> 809 <span class="hljs-comment">// Always return an object of the form {source: <string|buffer>}.</span> 810 <span class="hljs-keyword">return</span> { 811 <span class="hljs-attr">source</span>: <span class="hljs-string">'...'</span>, 812 }; 813 } 814 <span class="hljs-comment">// Defer to Node.js for all other URLs.</span> 815 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultGetSource</span>(url, context, defaultGetSource); 816}</code></pre> 817<h5><code>transformSource(source, context, defaultTransformSource)</code><span><a class="mark" href="#esm_transformsource_source_context_defaulttransformsource" id="esm_transformsource_source_context_defaulttransformsource">#</a></span></h5> 818<blockquote> 819<p>Note: The loaders API is being redesigned. This hook may disappear or its 820signature may change. Do not rely on the API described below.</p> 821</blockquote> 822<ul> 823<li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> 824<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 825<ul> 826<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 827<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 828</ul> 829</li> 830<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 831<ul> 832<li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> 833</ul> 834</li> 835</ul> 836<p>The <code>transformSource</code> hook provides a way to modify the source code of a loaded 837ES module file after the source string has been loaded but before Node.js has 838done anything with it.</p> 839<p>If this hook is used to convert unknown-to-Node.js file types into executable 840JavaScript, a resolve hook is also necessary in order to register any 841unknown-to-Node.js file extensions. See the <a href="#esm_transpiler_loader">transpiler loader example</a> below.</p> 842<pre><code class="language-js"><span class="hljs-comment">/** 843 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">!(string | SharedArrayBuffer | Uint8Array)</span>} <span class="hljs-variable">source</span> 844 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">{ 845 * format: string, 846 * url: string, 847 * </span>}} context 848 * <span class="hljs-doctag">@param</span> {<span class="hljs-type">Function</span>} <span class="hljs-variable">defaultTransformSource</span> 849 * <span class="hljs-doctag">@returns</span> {<span class="hljs-type">Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) </span>}>} 850 */</span> 851<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">transformSource</span>(<span class="hljs-params">source, context, defaultTransformSource</span>) { 852 <span class="hljs-keyword">const</span> { url, format } = context; 853 <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> 854 <span class="hljs-comment">// For some or all URLs, do some custom logic for modifying the source.</span> 855 <span class="hljs-comment">// Always return an object of the form {source: <string|buffer>}.</span> 856 <span class="hljs-keyword">return</span> { 857 <span class="hljs-attr">source</span>: <span class="hljs-string">'...'</span>, 858 }; 859 } 860 <span class="hljs-comment">// Defer to Node.js for all other sources.</span> 861 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultTransformSource</span>(source, context, defaultTransformSource); 862}</code></pre> 863<h5><code>getGlobalPreloadCode()</code><span><a class="mark" href="#esm_getglobalpreloadcode" id="esm_getglobalpreloadcode">#</a></span></h5> 864<blockquote> 865<p>Note: The loaders API is being redesigned. This hook may disappear or its 866signature may change. Do not rely on the API described below.</p> 867</blockquote> 868<ul> 869<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 870</ul> 871<p>Sometimes it might be necessary to run some code inside of the same global scope 872that the application runs in. This hook allows the return of a string that is 873run as sloppy-mode script on startup.</p> 874<p>Similar to how CommonJS wrappers work, the code runs in an implicit function 875scope. The only argument is a <code>require</code>-like function that can be used to load 876builtins like "fs": <code>getBuiltin(request: string)</code>.</p> 877<p>If the code needs more advanced <code>require</code> features, it has to construct 878its own <code>require</code> using <code>module.createRequire()</code>.</p> 879<pre><code class="language-js"><span class="hljs-comment">/** 880 * <span class="hljs-doctag">@returns</span> {<span class="hljs-type">string</span>} Code to run before application startup 881 */</span> 882<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getGlobalPreloadCode</span>(<span class="hljs-params"></span>) { 883 <span class="hljs-keyword">return</span> <span class="hljs-string">`\ 884globalThis.someInjectedProperty = 42; 885console.log('I just set some globals!'); 886 887const { createRequire } = getBuiltin('module'); 888 889const require = createRequire(process.cwd() + '/<preload>'); 890// [...] 891`</span>; 892}</code></pre> 893<h4>Examples<span><a class="mark" href="#esm_examples" id="esm_examples">#</a></span></h4> 894<p>The various loader hooks can be used together to accomplish wide-ranging 895customizations of Node.js’ code loading and evaluation behaviors.</p> 896<h5>HTTPS loader<span><a class="mark" href="#esm_https_loader" id="esm_https_loader">#</a></span></h5> 897<p>In current Node.js, specifiers starting with <code>https://</code> are unsupported. The 898loader below registers hooks to enable rudimentary support for such specifiers. 899While this may seem like a significant improvement to Node.js core 900functionality, there are substantial downsides to actually using this loader: 901performance is much slower than loading files from disk, there is no caching, 902and there is no security.</p> 903<pre><code class="language-js"><span class="hljs-comment">// https-loader.mjs</span> 904<span class="hljs-keyword">import</span> { get } <span class="hljs-keyword">from</span> <span class="hljs-string">'https'</span>; 905 906<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, defaultResolve</span>) { 907 <span class="hljs-keyword">const</span> { parentURL = <span class="hljs-literal">null</span> } = context; 908 909 <span class="hljs-comment">// Normally Node.js would error on specifiers starting with 'https://', so</span> 910 <span class="hljs-comment">// this hook intercepts them and converts them into absolute URLs to be</span> 911 <span class="hljs-comment">// passed along to the later hooks below.</span> 912 <span class="hljs-keyword">if</span> (specifier.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'https://'</span>)) { 913 <span class="hljs-keyword">return</span> { 914 <span class="hljs-attr">url</span>: specifier 915 }; 916 } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (parentURL && parentURL.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'https://'</span>)) { 917 <span class="hljs-keyword">return</span> { 918 <span class="hljs-attr">url</span>: <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier, parentURL).<span class="hljs-property">href</span> 919 }; 920 } 921 922 <span class="hljs-comment">// Let Node.js handle all other specifiers.</span> 923 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultResolve</span>(specifier, context, defaultResolve); 924} 925 926<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getFormat</span>(<span class="hljs-params">url, context, defaultGetFormat</span>) { 927 <span class="hljs-comment">// This loader assumes all network-provided JavaScript is ES module code.</span> 928 <span class="hljs-keyword">if</span> (url.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'https://'</span>)) { 929 <span class="hljs-keyword">return</span> { 930 <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span> 931 }; 932 } 933 934 <span class="hljs-comment">// Let Node.js handle all other URLs.</span> 935 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultGetFormat</span>(url, context, defaultGetFormat); 936} 937 938<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getSource</span>(<span class="hljs-params">url, context, defaultGetSource</span>) { 939 <span class="hljs-comment">// For JavaScript to be loaded over the network, we need to fetch and</span> 940 <span class="hljs-comment">// return it.</span> 941 <span class="hljs-keyword">if</span> (url.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'https://'</span>)) { 942 <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> { 943 <span class="hljs-title function_">get</span>(url, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> { 944 <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>; 945 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); 946 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>({ <span class="hljs-attr">source</span>: data })); 947 }).<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)); 948 }); 949 } 950 951 <span class="hljs-comment">// Let Node.js handle all other URLs.</span> 952 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultGetSource</span>(url, context, defaultGetSource); 953}</code></pre> 954<pre><code class="language-js"><span class="hljs-comment">// main.mjs</span> 955<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>; 956 957<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable constant_">VERSION</span>);</code></pre> 958<p>With the preceding loader, running 959<code>node --experimental-loader ./https-loader.mjs ./main.mjs</code> 960prints the current version of CoffeeScript per the module at the URL in 961<code>main.mjs</code>.</p> 962<h5>Transpiler loader<span><a class="mark" href="#esm_transpiler_loader" id="esm_transpiler_loader">#</a></span></h5> 963<p>Sources that are in formats Node.js doesn’t understand can be converted into 964JavaScript using the <a href="#esm_transformsource_source_context_defaulttransformsource"><code>transformSource</code> hook</a>. Before that hook gets called, 965however, other hooks need to tell Node.js not to throw an error on unknown file 966types; and to tell Node.js how to load this new file type.</p> 967<p>This is less performant than transpiling source files before running 968Node.js; a transpiler loader should only be used for development and testing 969purposes.</p> 970<pre><code class="language-js"><span class="hljs-comment">// coffeescript-loader.mjs</span> 971<span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">URL</span>, pathToFileURL } <span class="hljs-keyword">from</span> <span class="hljs-string">'url'</span>; 972<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>; 973 974<span class="hljs-keyword">const</span> baseURL = <span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-string">`<span class="hljs-subst">${process.cwd()}</span>/`</span>).<span class="hljs-property">href</span>; 975 976<span class="hljs-comment">// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.</span> 977<span class="hljs-keyword">const</span> extensionsRegex = <span class="hljs-regexp">/\.coffee$|\.litcoffee$|\.coffee\.md$/</span>; 978 979<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, defaultResolve</span>) { 980 <span class="hljs-keyword">const</span> { parentURL = baseURL } = context; 981 982 <span class="hljs-comment">// Node.js normally errors on unknown file extensions, so return a URL for</span> 983 <span class="hljs-comment">// specifiers ending in the CoffeeScript file extensions.</span> 984 <span class="hljs-keyword">if</span> (extensionsRegex.<span class="hljs-title function_">test</span>(specifier)) { 985 <span class="hljs-keyword">return</span> { 986 <span class="hljs-attr">url</span>: <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier, parentURL).<span class="hljs-property">href</span> 987 }; 988 } 989 990 <span class="hljs-comment">// Let Node.js handle all other specifiers.</span> 991 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultResolve</span>(specifier, context, defaultResolve); 992} 993 994<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getFormat</span>(<span class="hljs-params">url, context, defaultGetFormat</span>) { 995 <span class="hljs-comment">// Now that we patched resolve to let CoffeeScript URLs through, we need to</span> 996 <span class="hljs-comment">// tell Node.js what format such URLs should be interpreted as. For the</span> 997 <span class="hljs-comment">// purposes of this loader, all CoffeeScript URLs are ES modules.</span> 998 <span class="hljs-keyword">if</span> (extensionsRegex.<span class="hljs-title function_">test</span>(url)) { 999 <span class="hljs-keyword">return</span> { 1000 <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span> 1001 }; 1002 } 1003 1004 <span class="hljs-comment">// Let Node.js handle all other URLs.</span> 1005 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultGetFormat</span>(url, context, defaultGetFormat); 1006} 1007 1008<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">transformSource</span>(<span class="hljs-params">source, context, defaultTransformSource</span>) { 1009 <span class="hljs-keyword">const</span> { url, format } = context; 1010 1011 <span class="hljs-keyword">if</span> (extensionsRegex.<span class="hljs-title function_">test</span>(url)) { 1012 <span class="hljs-keyword">return</span> { 1013 <span class="hljs-attr">source</span>: <span class="hljs-title class_">CoffeeScript</span>.<span class="hljs-title function_">compile</span>(source, { <span class="hljs-attr">bare</span>: <span class="hljs-literal">true</span> }) 1014 }; 1015 } 1016 1017 <span class="hljs-comment">// Let Node.js handle all other sources.</span> 1018 <span class="hljs-keyword">return</span> <span class="hljs-title function_">defaultTransformSource</span>(source, context, defaultTransformSource); 1019}</code></pre> 1020<pre><code class="language-coffee"><span class="hljs-comment"># main.coffee</span> 1021<span class="hljs-keyword">import</span> { scream } <span class="hljs-keyword">from</span> <span class="hljs-string">'./scream.coffee'</span> 1022console.log scream <span class="hljs-string">'hello, world'</span> 1023 1024<span class="hljs-keyword">import</span> { version } <span class="hljs-keyword">from</span> <span class="hljs-string">'process'</span> 1025console.log <span class="hljs-string">"Brought to you by Node.js version <span class="hljs-subst">#{version}</span>"</span></code></pre> 1026<pre><code class="language-coffee"><span class="hljs-comment"># scream.coffee</span> 1027<span class="hljs-keyword">export</span> scream = <span class="hljs-function"><span class="hljs-params">(str)</span> -></span> str.toUpperCase()</code></pre> 1028<p>With the preceding loader, running 1029<code>node --experimental-loader ./coffeescript-loader.mjs main.coffee</code> 1030causes <code>main.coffee</code> to be turned into JavaScript after its source code is 1031loaded from disk but before Node.js executes it; and so on for any <code>.coffee</code>, 1032<code>.litcoffee</code> or <code>.coffee.md</code> files referenced via <code>import</code> statements of any 1033loaded file.</p> 1034</section><section><h3>Resolution algorithm<span><a class="mark" href="#esm_resolution_algorithm" id="esm_resolution_algorithm">#</a></span></h3> 1035<h4>Features<span><a class="mark" href="#esm_features" id="esm_features">#</a></span></h4> 1036<p>The resolver has the following properties:</p> 1037<ul> 1038<li>FileURL-based resolution as is used by ES modules</li> 1039<li>Support for builtin module loading</li> 1040<li>Relative and absolute URL resolution</li> 1041<li>No default extensions</li> 1042<li>No folder mains</li> 1043<li>Bare specifier package resolution lookup through node_modules</li> 1044</ul> 1045<h4>Resolver algorithm<span><a class="mark" href="#esm_resolver_algorithm" id="esm_resolver_algorithm">#</a></span></h4> 1046<p>The algorithm to load an ES module specifier is given through the 1047<strong>ESM_RESOLVE</strong> method below. It returns the resolved URL for a 1048module specifier relative to a parentURL.</p> 1049<p>The algorithm to determine the module format of a resolved URL is 1050provided by <strong>ESM_FORMAT</strong>, which returns the unique module 1051format for any file. The <em>"module"</em> format is returned for an ECMAScript 1052Module, while the <em>"commonjs"</em> format is used to indicate loading through the 1053legacy CommonJS loader. Additional formats such as <em>"addon"</em> can be extended in 1054future updates.</p> 1055<p>In the following algorithms, all subroutine errors are propagated as errors 1056of these top-level routines unless stated otherwise.</p> 1057<p><em>defaultConditions</em> is the conditional environment name array, 1058<code>["node", "import"]</code>.</p> 1059<p>The resolver can throw the following errors:</p> 1060<ul> 1061<li><em>Invalid Module Specifier</em>: Module specifier is an invalid URL, package name 1062or package subpath specifier.</li> 1063<li><em>Invalid Package Configuration</em>: package.json configuration is invalid or 1064contains an invalid configuration.</li> 1065<li><em>Invalid Package Target</em>: Package exports or imports define a target module 1066for the package that is an invalid type or string target.</li> 1067<li><em>Package Path Not Exported</em>: Package exports do not define or permit a target 1068subpath in the package for the given module.</li> 1069<li><em>Package Import Not Defined</em>: Package imports do not define the specifier.</li> 1070<li><em>Module Not Found</em>: The package or module requested does not exist.</li> 1071<li><em>Unsupported Directory Import</em>: The resolved path corresponds to a directory, 1072which is not a supported target for module imports.</li> 1073</ul> 1074<h4>Resolver Algorithm Specification<span><a class="mark" href="#esm_resolver_algorithm_specification" id="esm_resolver_algorithm_specification">#</a></span></h4> 1075<p><strong>ESM_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>)</p> 1076<blockquote> 1077<ol> 1078<li>Let <em>resolved</em> be <strong>undefined</strong>.</li> 1079<li>If <em>specifier</em> is a valid URL, then 1080<ol> 1081<li>Set <em>resolved</em> to the result of parsing and reserializing 1082<em>specifier</em> as a URL.</li> 1083</ol> 1084</li> 1085<li>Otherwise, if <em>specifier</em> starts with <em>"/"</em>, <em>"./"</em> or <em>"../"</em>, then 1086<ol> 1087<li>Set <em>resolved</em> to the URL resolution of <em>specifier</em> relative to 1088<em>parentURL</em>.</li> 1089</ol> 1090</li> 1091<li>Otherwise, if <em>specifier</em> starts with <em>"#"</em>, then 1092<ol> 1093<li>Set <em>resolved</em> to the destructured value of the result of 1094<strong>PACKAGE_IMPORTS_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>, 1095<em>defaultConditions</em>).</li> 1096</ol> 1097</li> 1098<li>Otherwise, 1099<ol> 1100<li>Note: <em>specifier</em> is now a bare specifier.</li> 1101<li>Set <em>resolved</em> the result of 1102<strong>PACKAGE_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>).</li> 1103</ol> 1104</li> 1105<li>If <em>resolved</em> contains any percent encodings of <em>"/"</em> or <em>"\"</em> (<em>"%2f"</em> 1106and <em>"%5C"</em> respectively), then 1107<ol> 1108<li>Throw an <em>Invalid Module Specifier</em> error.</li> 1109</ol> 1110</li> 1111<li>If the file at <em>resolved</em> is a directory, then 1112<ol> 1113<li>Throw an <em>Unsupported Directory Import</em> error.</li> 1114</ol> 1115</li> 1116<li>If the file at <em>resolved</em> does not exist, then 1117<ol> 1118<li>Throw a <em>Module Not Found</em> error.</li> 1119</ol> 1120</li> 1121<li>Set <em>resolved</em> to the real path of <em>resolved</em>.</li> 1122<li>Let <em>format</em> be the result of <strong>ESM_FORMAT</strong>(<em>resolved</em>).</li> 1123<li>Load <em>resolved</em> as module format, <em>format</em>.</li> 1124<li>Return <em>resolved</em>.</li> 1125</ol> 1126</blockquote> 1127<p><strong>PACKAGE_RESOLVE</strong>(<em>packageSpecifier</em>, <em>parentURL</em>)</p> 1128<blockquote> 1129<ol> 1130<li>Let <em>packageName</em> be <strong>undefined</strong>.</li> 1131<li>If <em>packageSpecifier</em> is an empty string, then 1132<ol> 1133<li>Throw an <em>Invalid Module Specifier</em> error.</li> 1134</ol> 1135</li> 1136<li>If <em>packageSpecifier</em> does not start with <em>"@"</em>, then 1137<ol> 1138<li>Set <em>packageName</em> to the substring of <em>packageSpecifier</em> until the first 1139<em>"/"</em> separator or the end of the string.</li> 1140</ol> 1141</li> 1142<li>Otherwise, 1143<ol> 1144<li>If <em>packageSpecifier</em> does not contain a <em>"/"</em> separator, then 1145<ol> 1146<li>Throw an <em>Invalid Module Specifier</em> error.</li> 1147</ol> 1148</li> 1149<li>Set <em>packageName</em> to the substring of <em>packageSpecifier</em> 1150until the second <em>"/"</em> separator or the end of the string.</li> 1151</ol> 1152</li> 1153<li>If <em>packageName</em> starts with <em>"."</em> or contains <em>"\"</em> or <em>"%"</em>, then 1154<ol> 1155<li>Throw an <em>Invalid Module Specifier</em> error.</li> 1156</ol> 1157</li> 1158<li>Let <em>packageSubpath</em> be <em>"."</em> concatenated with the substring of 1159<em>packageSpecifier</em> from the position at the length of <em>packageName</em>.</li> 1160<li>Let <em>selfUrl</em> be the result of 1161<strong>PACKAGE_SELF_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>).</li> 1162<li>If <em>selfUrl</em> is not <strong>undefined</strong>, return <em>selfUrl</em>.</li> 1163<li>If <em>packageSubpath</em> is <em>"."</em> and <em>packageName</em> is a Node.js builtin 1164module, then 1165<ol> 1166<li>Return the string <em>"node:"</em> concatenated with <em>packageSpecifier</em>.</li> 1167</ol> 1168</li> 1169<li>While <em>parentURL</em> is not the file system root, 1170<ol> 1171<li>Let <em>packageURL</em> be the URL resolution of <em>"node_modules/"</em> 1172concatenated with <em>packageSpecifier</em>, relative to <em>parentURL</em>.</li> 1173<li>Set <em>parentURL</em> to the parent folder URL of <em>parentURL</em>.</li> 1174<li>If the folder at <em>packageURL</em> does not exist, then 1175<ol> 1176<li>Set <em>parentURL</em> to the parent URL path of <em>parentURL</em>.</li> 1177<li>Continue the next loop iteration.</li> 1178</ol> 1179</li> 1180<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li> 1181<li>If <em>pjson</em> is not <strong>null</strong> and <em>pjson</em>.<em>exports</em> is not <strong>null</strong> or 1182<strong>undefined</strong>, then 1183<ol> 1184<li>Let <em>exports</em> be <em>pjson.exports</em>.</li> 1185<li>Return the <em>resolved</em> destructured value of the result of 1186<strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>packageSubpath</em>, 1187<em>pjson.exports</em>, <em>defaultConditions</em>).</li> 1188</ol> 1189</li> 1190<li>Otherwise, if <em>packageSubpath</em> is equal to <em>"."</em>, then 1191<ol> 1192<li>Return the result applying the legacy <strong>LOAD_AS_DIRECTORY</strong> 1193CommonJS resolver to <em>packageURL</em>, throwing a <em>Module Not Found</em> 1194error for no resolution.</li> 1195</ol> 1196</li> 1197<li>Otherwise, 1198<ol> 1199<li>Return the URL resolution of <em>packageSubpath</em> in <em>packageURL</em>.</li> 1200</ol> 1201</li> 1202</ol> 1203</li> 1204<li>Throw a <em>Module Not Found</em> error.</li> 1205</ol> 1206</blockquote> 1207<p><strong>PACKAGE_SELF_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>)</p> 1208<blockquote> 1209<ol> 1210<li>Let <em>packageURL</em> be the result of <strong>READ_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li> 1211<li>If <em>packageURL</em> is <strong>null</strong>, then 1212<ol> 1213<li>Return <strong>undefined</strong>.</li> 1214</ol> 1215</li> 1216<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li> 1217<li>If <em>pjson</em> is <strong>null</strong> or if <em>pjson</em>.<em>exports</em> is <strong>null</strong> or 1218<strong>undefined</strong>, then 1219<ol> 1220<li>Return <strong>undefined</strong>.</li> 1221</ol> 1222</li> 1223<li>If <em>pjson.name</em> is equal to <em>packageName</em>, then 1224<ol> 1225<li>Return the <em>resolved</em> destructured value of the result of 1226<strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>subpath</em>, <em>pjson.exports</em>, 1227<em>defaultConditions</em>).</li> 1228</ol> 1229</li> 1230<li>Otherwise, return <strong>undefined</strong>.</li> 1231</ol> 1232</blockquote> 1233<p><strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>subpath</em>, <em>exports</em>, <em>conditions</em>)</p> 1234<blockquote> 1235<ol> 1236<li>If <em>exports</em> is an Object with both a key starting with <em>"."</em> and a key not 1237starting with <em>"."</em>, throw an <em>Invalid Package Configuration</em> error.</li> 1238<li>If <em>subpath</em> is equal to <em>"."</em>, then 1239<ol> 1240<li>Let <em>mainExport</em> be <strong>undefined</strong>.</li> 1241<li>If <em>exports</em> is a String or Array, or an Object containing no keys 1242starting with <em>"."</em>, then 1243<ol> 1244<li>Set <em>mainExport</em> to <em>exports</em>.</li> 1245</ol> 1246</li> 1247<li>Otherwise if <em>exports</em> is an Object containing a <em>"."</em> property, then 1248<ol> 1249<li>Set <em>mainExport</em> to <em>exports</em>[<em>"."</em>].</li> 1250</ol> 1251</li> 1252<li>If <em>mainExport</em> is not <strong>undefined</strong>, then 1253<ol> 1254<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>( 1255<em>packageURL</em>, <em>mainExport</em>, <em>""</em>, <strong>false</strong>, <strong>false</strong>, 1256<em>conditions</em>).</li> 1257<li>If <em>resolved</em> is not <strong>null</strong> or <strong>undefined</strong>, then 1258<ol> 1259<li>Return <em>resolved</em>.</li> 1260</ol> 1261</li> 1262</ol> 1263</li> 1264</ol> 1265</li> 1266<li>Otherwise, if <em>exports</em> is an Object and all keys of <em>exports</em> start with 1267<em>"."</em>, then 1268<ol> 1269<li>Let <em>matchKey</em> be the string <em>"./"</em> concatenated with <em>subpath</em>.</li> 1270<li>Let <em>resolvedMatch</em> be result of <strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>( 1271<em>matchKey</em>, <em>exports</em>, <em>packageURL</em>, <strong>false</strong>, <em>conditions</em>).</li> 1272<li>If <em>resolvedMatch</em>.<em>resolve</em> is not <strong>null</strong> or <strong>undefined</strong>, then 1273<ol> 1274<li>Return <em>resolvedMatch</em>.</li> 1275</ol> 1276</li> 1277</ol> 1278</li> 1279<li>Throw a <em>Package Path Not Exported</em> error.</li> 1280</ol> 1281</blockquote> 1282<p><strong>PACKAGE_IMPORTS_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>, <em>conditions</em>)</p> 1283<blockquote> 1284<ol> 1285<li>Assert: <em>specifier</em> begins with <em>"#"</em>.</li> 1286<li>If <em>specifier</em> is exactly equal to <em>"#"</em> or starts with <em>"#/"</em>, then 1287<ol> 1288<li>Throw an <em>Invalid Module Specifier</em> error.</li> 1289</ol> 1290</li> 1291<li>Let <em>packageURL</em> be the result of <strong>READ_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li> 1292<li>If <em>packageURL</em> is not <strong>null</strong>, then 1293<ol> 1294<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li> 1295<li>If <em>pjson.imports</em> is a non-null Object, then 1296<ol> 1297<li>Let <em>resolvedMatch</em> be the result of 1298<strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(<em>specifier</em>, <em>pjson.imports</em>, 1299<em>packageURL</em>, <strong>true</strong>, <em>conditions</em>).</li> 1300<li>If <em>resolvedMatch</em>.<em>resolve</em> is not <strong>null</strong> or <strong>undefined</strong>, then 1301<ol> 1302<li>Return <em>resolvedMatch</em>.</li> 1303</ol> 1304</li> 1305</ol> 1306</li> 1307</ol> 1308</li> 1309<li>Throw a <em>Package Import Not Defined</em> error.</li> 1310</ol> 1311</blockquote> 1312<p><strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(<em>matchKey</em>, <em>matchObj</em>, <em>packageURL</em>, 1313<em>isImports</em>, <em>conditions</em>)</p> 1314<blockquote> 1315<ol> 1316<li>If <em>matchKey</em> is a key of <em>matchObj</em> and does not end in <em>"/"</em> or contain 1317<em>"*"</em>, then 1318<ol> 1319<li>Let <em>target</em> be the value of <em>matchObj</em>[<em>matchKey</em>].</li> 1320<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>( 1321<em>packageURL</em>, <em>target</em>, <em>""</em>, <strong>false</strong>, <em>isImports</em>, <em>conditions</em>).</li> 1322<li>Return the object <em>{ resolved, exact: <strong>true</strong> }</em>.</li> 1323</ol> 1324</li> 1325<li>Let <em>expansionKeys</em> be the list of keys of <em>matchObj</em> either ending in 1326<em>"/"</em> or containing only a single <em>"*"</em>, sorted by the sorting function 1327<strong>PATTERN_KEY_COMPARE</strong> which orders in descending order of specificity.</li> 1328<li>For each key <em>expansionKey</em> in <em>expansionKeys</em>, do 1329<ol> 1330<li>Let <em>patternBase</em> be <strong>null</strong>.</li> 1331<li>If <em>expansionKey</em> contains <em>"*"</em>, set <em>patternBase</em> to the substring of 1332<em>expansionKey</em> up to but excluding the first <em>"*"</em> character.</li> 1333<li>If <em>patternBase</em> is not <strong>null</strong> and <em>matchKey</em> starts with but is not 1334equal to <em>patternBase</em>, then 1335<ol> 1336<li>Let <em>patternTrailer</em> be the substring of <em>expansionKey</em> from the 1337index after the first <em>"*"</em> character.</li> 1338<li>If <em>patternTrailer</em> has zero length, or if <em>matchKey</em> ends with 1339<em>patternTrailer</em> and the length of <em>matchKey</em> is greater than or 1340equal to the length of <em>expansionKey</em>, then 1341<ol> 1342<li>Let <em>target</em> be the value of <em>matchObj</em>[<em>expansionKey</em>].</li> 1343<li>Let <em>subpath</em> be the substring of <em>matchKey</em> starting at the 1344index of the length of <em>patternBase</em> up to the length of 1345<em>matchKey</em> minus the length of <em>patternTrailer</em>.</li> 1346<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>( 1347<em>packageURL</em>, <em>target</em>, <em>subpath</em>, <strong>true</strong>, <em>isImports</em>, 1348<em>conditions</em>).</li> 1349<li>Return the object <em>{ resolved, exact: <strong>true</strong> }</em>.</li> 1350</ol> 1351</li> 1352</ol> 1353</li> 1354<li>Otherwise if <em>patternBase</em> is <strong>null</strong> and <em>matchKey</em> starts with 1355<em>expansionKey</em>, then 1356<ol> 1357<li>Let <em>target</em> be the value of <em>matchObj</em>[<em>expansionKey</em>].</li> 1358<li>Let <em>subpath</em> be the substring of <em>matchKey</em> starting at the 1359index of the length of <em>expansionKey</em>.</li> 1360<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>( 1361<em>packageURL</em>, <em>target</em>, <em>subpath</em>, <strong>false</strong>, <em>isImports</em>, 1362<em>conditions</em>).</li> 1363<li>Return the object <em>{ resolved, exact: <strong>false</strong> }</em>.</li> 1364</ol> 1365</li> 1366</ol> 1367</li> 1368<li>Return the object <em>{ resolved: <strong>null</strong>, exact: <strong>true</strong> }</em>.</li> 1369</ol> 1370</blockquote> 1371<p><strong>PATTERN_KEY_COMPARE</strong>(<em>keyA</em>, <em>keyB</em>)</p> 1372<blockquote> 1373<ol> 1374<li>Assert: <em>keyA</em> ends with <em>"/"</em> or contains only a single <em>"*"</em>.</li> 1375<li>Assert: <em>keyB</em> ends with <em>"/"</em> or contains only a single <em>"*"</em>.</li> 1376<li>Let <em>baseLengthA</em> be the index of <em>"*"</em> in <em>keyA</em> plus one, if <em>keyA</em> 1377contains <em>"*"</em>, or the length of <em>keyA</em> otherwise.</li> 1378<li>Let <em>baseLengthB</em> be the index of <em>"*"</em> in <em>keyB</em> plus one, if <em>keyB</em> 1379contains <em>"*"</em>, or the length of <em>keyB</em> otherwise.</li> 1380<li>If <em>baseLengthA</em> is greater than <em>baseLengthB</em>, return -1.</li> 1381<li>If <em>baseLengthB</em> is greater than <em>baseLengthA</em>, return 1.</li> 1382<li>If <em>keyA</em> does not contain <em>"*"</em>, return 1.</li> 1383<li>If <em>keyB</em> does not contain <em>"*"</em>, return -1.</li> 1384<li>If the length of <em>keyA</em> is greater than the length of <em>keyB</em>, return -1.</li> 1385<li>If the length of <em>keyB</em> is greater than the length of <em>keyA</em>, return 1.</li> 1386<li>Return 0.</li> 1387</ol> 1388</blockquote> 1389<p><strong>PACKAGE_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>, <em>subpath</em>, <em>pattern</em>, 1390<em>internal</em>, <em>conditions</em>)</p> 1391<blockquote> 1392<ol> 1393<li>If <em>target</em> is a String, then 1394<ol> 1395<li>If <em>pattern</em> is <strong>false</strong>, <em>subpath</em> has non-zero length and <em>target</em> 1396does not end with <em>"/"</em>, throw an <em>Invalid Module Specifier</em> error.</li> 1397<li>If <em>target</em> does not start with <em>"./"</em>, then 1398<ol> 1399<li>If <em>internal</em> is <strong>true</strong> and <em>target</em> does not start with <em>"../"</em> or 1400<em>"/"</em> and is not a valid URL, then 1401<ol> 1402<li>If <em>pattern</em> is <strong>true</strong>, then 1403<ol> 1404<li>Return <strong>PACKAGE_RESOLVE</strong>(<em>target</em> with every instance of 1405<em>"*"</em> replaced by <em>subpath</em>, <em>packageURL</em> + <em>"/"</em>)_.</li> 1406</ol> 1407</li> 1408<li>Return <strong>PACKAGE_RESOLVE</strong>(<em>target</em> + <em>subpath</em>, 1409<em>packageURL</em> + <em>"/"</em>)_.</li> 1410</ol> 1411</li> 1412<li>Otherwise, throw an <em>Invalid Package Target</em> error.</li> 1413</ol> 1414</li> 1415<li>If <em>target</em> split on <em>"/"</em> or <em>"\"</em> contains any <em>"."</em>, <em>".."</em> or 1416<em>"node_modules"</em> segments after the first segment, throw an 1417<em>Invalid Package Target</em> error.</li> 1418<li>Let <em>resolvedTarget</em> be the URL resolution of the concatenation of 1419<em>packageURL</em> and <em>target</em>.</li> 1420<li>Assert: <em>resolvedTarget</em> is contained in <em>packageURL</em>.</li> 1421<li>If <em>subpath</em> split on <em>"/"</em> or <em>"\"</em> contains any <em>"."</em>, <em>".."</em> or 1422<em>"node_modules"</em> segments, throw an <em>Invalid Module Specifier</em> error.</li> 1423<li>If <em>pattern</em> is <strong>true</strong>, then 1424<ol> 1425<li>Return the URL resolution of <em>resolvedTarget</em> with every instance of 1426<em>"*"</em> replaced with <em>subpath</em>.</li> 1427</ol> 1428</li> 1429<li>Otherwise, 1430<ol> 1431<li>Return the URL resolution of the concatenation of <em>subpath</em> and 1432<em>resolvedTarget</em>.</li> 1433</ol> 1434</li> 1435</ol> 1436</li> 1437<li>Otherwise, if <em>target</em> is a non-null Object, then 1438<ol> 1439<li>If <em>exports</em> contains any index property keys, as defined in ECMA-262 1440<a href="https://tc39.es/ecma262/#integer-index">6.1.7 Array Index</a>, throw an <em>Invalid Package Configuration</em> error.</li> 1441<li>For each property <em>p</em> of <em>target</em>, in object insertion order as, 1442<ol> 1443<li>If <em>p</em> equals <em>"default"</em> or <em>conditions</em> contains an entry for <em>p</em>, 1444then 1445<ol> 1446<li>Let <em>targetValue</em> be the value of the <em>p</em> property in <em>target</em>.</li> 1447<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>( 1448<em>packageURL</em>, <em>targetValue</em>, <em>subpath</em>, <em>pattern</em>, <em>internal</em>, 1449<em>conditions</em>).</li> 1450<li>If <em>resolved</em> is equal to <strong>undefined</strong>, continue the loop.</li> 1451<li>Return <em>resolved</em>.</li> 1452</ol> 1453</li> 1454</ol> 1455</li> 1456<li>Return <strong>undefined</strong>.</li> 1457</ol> 1458</li> 1459<li>Otherwise, if <em>target</em> is an Array, then 1460<ol> 1461<li>If _target.length is zero, return <strong>null</strong>.</li> 1462<li>For each item <em>targetValue</em> in <em>target</em>, do 1463<ol> 1464<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>( 1465<em>packageURL</em>, <em>targetValue</em>, <em>subpath</em>, <em>pattern</em>, <em>internal</em>, 1466<em>conditions</em>), continuing the loop on any <em>Invalid Package Target</em> 1467error.</li> 1468<li>If <em>resolved</em> is <strong>undefined</strong>, continue the loop.</li> 1469<li>Return <em>resolved</em>.</li> 1470</ol> 1471</li> 1472<li>Return or throw the last fallback resolution <strong>null</strong> return or error.</li> 1473</ol> 1474</li> 1475<li>Otherwise, if <em>target</em> is <em>null</em>, return <strong>null</strong>.</li> 1476<li>Otherwise throw an <em>Invalid Package Target</em> error.</li> 1477</ol> 1478</blockquote> 1479<p><strong>ESM_FORMAT</strong>(<em>url</em>)</p> 1480<blockquote> 1481<ol> 1482<li>Assert: <em>url</em> corresponds to an existing file.</li> 1483<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_SCOPE</strong>(<em>url</em>).</li> 1484<li>If <em>url</em> ends in <em>".mjs"</em>, then 1485<ol> 1486<li>Return <em>"module"</em>.</li> 1487</ol> 1488</li> 1489<li>If <em>url</em> ends in <em>".cjs"</em>, then 1490<ol> 1491<li>Return <em>"commonjs"</em>.</li> 1492</ol> 1493</li> 1494<li>If <em>pjson?.type</em> exists and is <em>"module"</em>, then 1495<ol> 1496<li>If <em>url</em> ends in <em>".js"</em>, then 1497<ol> 1498<li>Return <em>"module"</em>.</li> 1499</ol> 1500</li> 1501<li>Throw an <em>Unsupported File Extension</em> error.</li> 1502</ol> 1503</li> 1504<li>Otherwise, 1505<ol> 1506<li>Throw an <em>Unsupported File Extension</em> error.</li> 1507</ol> 1508</li> 1509</ol> 1510</blockquote> 1511<p><strong>READ_PACKAGE_SCOPE</strong>(<em>url</em>)</p> 1512<blockquote> 1513<ol> 1514<li>Let <em>scopeURL</em> be <em>url</em>.</li> 1515<li>While <em>scopeURL</em> is not the file system root, 1516<ol> 1517<li>Set <em>scopeURL</em> to the parent URL of <em>scopeURL</em>.</li> 1518<li>If <em>scopeURL</em> ends in a <em>"node_modules"</em> path segment, return <strong>null</strong>.</li> 1519<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>scopeURL</em>).</li> 1520<li>If <em>pjson</em> is not <strong>null</strong>, then 1521<ol> 1522<li>Return <em>pjson</em>.</li> 1523</ol> 1524</li> 1525</ol> 1526</li> 1527<li>Return <strong>null</strong>.</li> 1528</ol> 1529</blockquote> 1530<p><strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>)</p> 1531<blockquote> 1532<ol> 1533<li>Let <em>pjsonURL</em> be the resolution of <em>"package.json"</em> within <em>packageURL</em>.</li> 1534<li>If the file at <em>pjsonURL</em> does not exist, then 1535<ol> 1536<li>Return <strong>null</strong>.</li> 1537</ol> 1538</li> 1539<li>If the file at <em>packageURL</em> does not parse as valid JSON, then 1540<ol> 1541<li>Throw an <em>Invalid Package Configuration</em> error.</li> 1542</ol> 1543</li> 1544<li>Return the parsed JSON source of the file at <em>pjsonURL</em>.</li> 1545</ol> 1546</blockquote> 1547<h4>Customizing ESM specifier resolution algorithm<span><a class="mark" href="#esm_customizing_esm_specifier_resolution_algorithm" id="esm_customizing_esm_specifier_resolution_algorithm">#</a></span></h4> 1548<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> 1549<p>The current specifier resolution does not support all default behavior of 1550the CommonJS loader. One of the behavior differences is automatic resolution 1551of file extensions and the ability to import directories that have an index 1552file.</p> 1553<p>The <code>--experimental-specifier-resolution=[mode]</code> flag can be used to customize 1554the extension resolution algorithm. The default mode is <code>explicit</code>, which 1555requires the full path to a module be provided to the loader. To enable the 1556automatic extension resolution and importing from directories that include an 1557index file use the <code>node</code> mode.</p> 1558<pre><code class="language-console"><span class="hljs-meta">$ </span><span class="language-bash">node index.mjs</span> 1559success! 1560<span class="hljs-meta">$ </span><span class="language-bash">node index <span class="hljs-comment"># Failure!</span></span> 1561Error: Cannot find module 1562<span class="hljs-meta">$ </span><span class="language-bash">node --experimental-specifier-resolution=node index</span> 1563success!</code></pre> 1564<!-- Note: The cjs-module-lexer link should be kept in-sync with the deps version --></section> 1565 <!-- API END --> 1566 </div> 1567 </div> 1568 </div> 1569 <script> 1570 'use strict'; 1571 { 1572 const kCustomPreference = 'customDarkTheme'; 1573 const userSettings = sessionStorage.getItem(kCustomPreference); 1574 const themeToggleButton = document.getElementById('theme-toggle-btn'); 1575 if (userSettings === null && window.matchMedia) { 1576 const mq = window.matchMedia('(prefers-color-scheme: dark)'); 1577 if ('onchange' in mq) { 1578 function mqChangeListener(e) { 1579 document.body.classList.toggle('dark-mode', e.matches); 1580 } 1581 mq.addEventListener('change', mqChangeListener); 1582 if (themeToggleButton) { 1583 themeToggleButton.addEventListener('click', function() { 1584 mq.removeEventListener('change', mqChangeListener); 1585 }, { once: true }); 1586 } 1587 } 1588 if (mq.matches) { 1589 document.body.classList.add('dark-mode'); 1590 } 1591 } else if (userSettings === 'true') { 1592 document.body.classList.add('dark-mode'); 1593 } 1594 if (themeToggleButton) { 1595 themeToggleButton.hidden = false; 1596 themeToggleButton.addEventListener('click', function() { 1597 sessionStorage.setItem( 1598 kCustomPreference, 1599 document.body.classList.toggle('dark-mode') 1600 ); 1601 }); 1602 } 1603 } 1604 </script> 1605</body> 1606</html> 1607