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