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