The import.meta meta property is an Object that contains the following\nproperties.
import.meta
Object
This is defined exactly the same as it is in browsers providing the URL of the\ncurrent module file.
This enables useful patterns such as relative file loading:
import { readFileSync } from 'node:fs';\nconst buffer = readFileSync(new URL('./data.proto', import.meta.url));\n
\nStability: 1 - Experimental\n
Stability: 1 - Experimental
This feature is only available with the --experimental-import-meta-resolve\ncommand flag enabled.
--experimental-import-meta-resolve
specifier
parent
import.meta.url
Provides a module-relative resolution function scoped to each module, returning\nthe URL string.
const dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n
import.meta.resolve also accepts a second argument which is the parent module\nfrom which to resolve from:
import.meta.resolve
await import.meta.resolve('./dep', import.meta.url);\n
This function is asynchronous because the ES module resolver in Node.js is\nallowed to be asynchronous.
ECMAScript modules are the official standard format to package JavaScript\ncode for reuse. Modules are defined using a variety of import and\nexport statements.
import
export
The following example of an ES module exports a function:
// addTwo.mjs\nfunction addTwo(num) {\n return num + 2;\n}\n\nexport { addTwo };\n
The following example of an ES module imports the function from addTwo.mjs:
addTwo.mjs
// app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));\n
Node.js fully supports ECMAScript modules as they are currently specified and\nprovides interoperability between them and its original module format,\nCommonJS.
Node.js has two module systems: CommonJS modules and ECMAScript modules.
Authors can tell Node.js to use the ECMAScript modules loader\nvia the .mjs file extension, the package.json \"type\" field, or the\n--input-type flag. Outside of those cases, Node.js will use the CommonJS\nmodule loader. See Determining module system for more details.
.mjs
package.json
\"type\"
--input-type
This section was moved to Modules: Packages.
The specifier of an import statement is the string after the from keyword,\ne.g. 'node:path' in import { sep } from 'node:path'. Specifiers are also\nused in export from statements, and as the argument to an import()\nexpression.
from
'node:path'
import { sep } from 'node:path'
export from
import()
There are three types of specifiers:
Relative specifiers like './startup.js' or '../config.mjs'. They refer\nto a path relative to the location of the importing file. The file extension\nis always necessary for these.
'./startup.js'
'../config.mjs'
Bare specifiers like 'some-package' or 'some-package/shuffle'. They can\nrefer to the main entry point of a package by the package name, or a\nspecific feature module within a package prefixed by the package name as per\nthe examples respectively. Including the file extension is only necessary\nfor packages without an \"exports\" field.
'some-package'
'some-package/shuffle'
\"exports\"
Absolute specifiers like 'file:///opt/nodejs/config.js'. They refer\ndirectly and explicitly to a full path.
'file:///opt/nodejs/config.js'
Bare specifier resolutions are handled by the Node.js module resolution\nalgorithm. All other specifier resolutions are always only resolved with\nthe standard relative URL resolution semantics.
Like in CommonJS, module files within packages can be accessed by appending a\npath to the package name unless the package's package.json contains an\n\"exports\" field, in which case files within packages can only be accessed\nvia the paths defined in \"exports\".
For details on these package resolution rules that apply to bare specifiers in\nthe Node.js module resolution, see the packages documentation.
A file extension must be provided when using the import keyword to resolve\nrelative or absolute specifiers. Directory indexes (e.g. './startup/index.js')\nmust also be fully specified.
'./startup/index.js'
This behavior matches how import behaves in browser environments, assuming a\ntypically configured server.
ES modules are resolved and cached as URLs. This means that special characters\nmust be percent-encoded, such as # with %23 and ? with %3F.
#
%23
?
%3F
file:, node:, and data: URL schemes are supported. A specifier like\n'https://example.com/app.js' is not supported natively in Node.js unless using\na custom HTTPS loader.
file:
node:
data:
'https://example.com/app.js'
Modules are loaded multiple times if the import specifier used to resolve\nthem has a different query or fragment.
import './foo.mjs?query=1'; // loads ./foo.mjs with query of \"?query=1\"\nimport './foo.mjs?query=2'; // loads ./foo.mjs with query of \"?query=2\"\n
The volume root may be referenced via /, //, or file:///. Given the\ndifferences between URL and path resolution (such as percent encoding\ndetails), it is recommended to use url.pathToFileURL when importing a path.
/
//
file:///
data: URLs are supported for importing with the following MIME types:
text/javascript
application/json
application/wasm
import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"' assert { type: 'json' };\n
data: URLs only resolve bare specifiers for builtin modules\nand absolute specifiers. Resolving\nrelative specifiers does not work because data: is not a\nspecial scheme. For example, attempting to load ./foo\nfrom data:text/javascript,import \"./foo\"; fails to resolve because there\nis no concept of relative resolution for data: URLs.
./foo
data:text/javascript,import \"./foo\";
node: URLs are supported as an alternative means to load Node.js builtin\nmodules. This URL scheme allows for builtin modules to be referenced by valid\nabsolute URL strings.
import fs from 'node:fs/promises';\n
The Import Assertions proposal adds an inline syntax for module import\nstatements to pass on more information alongside the module specifier.
import fooData from './foo.json' assert { type: 'json' };\n\nconst { default: barData } =\n await import('./bar.json', { assert: { type: 'json' } });\n
Node.js supports the following type values, for which the assertion is\nmandatory:
type
'json'
Core modules provide named exports of their public API. A\ndefault export is also provided which is the value of the CommonJS exports.\nThe default export can be used for, among other things, modifying the named\nexports. Named exports of builtin modules are updated only by calling\nmodule.syncBuiltinESMExports().
module.syncBuiltinESMExports()
import EventEmitter from 'node:events';\nconst e = new EventEmitter();\n
import { readFile } from 'node:fs';\nreadFile('./foo.txt', (err, source) => {\n if (err) {\n console.error(err);\n } else {\n console.log(source);\n }\n});\n
import fs, { readFileSync } from 'node:fs';\nimport { syncBuiltinESMExports } from 'node:module';\nimport { Buffer } from 'node:buffer';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;\n
Dynamic import() is supported in both CommonJS and ES modules. In CommonJS\nmodules it can be used to load ES modules.
An import statement can reference an ES module or a CommonJS module.\nimport statements are permitted only in ES modules, but dynamic import()\nexpressions are supported in CommonJS for loading ES modules.
When importing CommonJS modules, the\nmodule.exports object is provided as the default export. Named exports may be\navailable, provided by static analysis as a convenience for better ecosystem\ncompatibility.
module.exports
The CommonJS module require always treats the files it references as CommonJS.
require
Using require to load an ES module is not supported because ES modules have\nasynchronous execution. Instead, use import() to load an ES module\nfrom a CommonJS module.
CommonJS modules consist of a module.exports object which can be of any type.
When importing a CommonJS module, it can be reliably imported using the ES\nmodule default import or its corresponding sugar syntax:
import { default as cjs } from 'cjs';\n\n// The following import statement is \"syntax sugar\" (equivalent but sweeter)\n// for `{ default as cjsSugar }` in the above import statement:\nimport cjsSugar from 'cjs';\n\nconsole.log(cjs);\nconsole.log(cjs === cjsSugar);\n// Prints:\n// <module.exports>\n// true\n
The ECMAScript Module Namespace representation of a CommonJS module is always\na namespace with a default export key pointing to the CommonJS\nmodule.exports value.
default
This Module Namespace Exotic Object can be directly observed either when using\nimport * as m from 'cjs' or a dynamic import:
import * as m from 'cjs'
import * as m from 'cjs';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n// [Module] { default: <module.exports> }\n// true\n
For better compatibility with existing usage in the JS ecosystem, Node.js\nin addition attempts to determine the CommonJS named exports of every imported\nCommonJS module to provide them as separate ES module exports using a static\nanalysis process.
For example, consider a CommonJS module written:
// cjs.cjs\nexports.name = 'exported';\n
The preceding module supports named imports in ES modules:
import { name } from './cjs.cjs';\nconsole.log(name);\n// Prints: 'exported'\n\nimport cjs from './cjs.cjs';\nconsole.log(cjs);\n// Prints: { name: 'exported' }\n\nimport * as m from './cjs.cjs';\nconsole.log(m);\n// Prints: [Module] { default: { name: 'exported' }, name: 'exported' }\n
As can be seen from the last example of the Module Namespace Exotic Object being\nlogged, the name export is copied off of the module.exports object and set\ndirectly on the ES module namespace when the module is imported.
name
Live binding updates or new exports added to module.exports are not detected\nfor these named exports.
The detection of named exports is based on common syntax patterns but does not\nalways correctly detect named exports. In these cases, using the default\nimport form described above can be a better option.
Named exports detection covers many common export patterns, reexport patterns\nand build tool and transpiler outputs. See cjs-module-lexer for the exact\nsemantics implemented.
In most cases, the ES module import can be used to load CommonJS modules.
If needed, a require function can be constructed within an ES module using\nmodule.createRequire().
module.createRequire()
These CommonJS variables are not available in ES modules.
__filename and __dirname use cases can be replicated via\nimport.meta.url.
__filename
__dirname
Native modules are not currently supported with ES module imports.
They can instead be loaded with module.createRequire() or\nprocess.dlopen.
process.dlopen
Relative resolution can be handled via new URL('./local', import.meta.url).
new URL('./local', import.meta.url)
For a complete require.resolve replacement, there is a flagged experimental\nimport.meta.resolve API.
require.resolve
Alternatively module.createRequire() can be used.
NODE_PATH is not part of resolving import specifiers. Please use symlinks\nif this behavior is desired.
NODE_PATH
require.extensions is not used by import. The expectation is that loader\nhooks can provide this workflow in the future.
require.extensions
require.cache is not used by import as the ES module loader has its own\nseparate cache.
require.cache
JSON files can be referenced by import:
import packageConfig from './package.json' assert { type: 'json' };\n
The assert { type: 'json' } syntax is mandatory; see Import Assertions.
assert { type: 'json' }
The imported JSON only exposes a default export. There is no support for named\nexports. A cache entry is created in the CommonJS cache to avoid duplication.\nThe same object is returned in CommonJS if the JSON module has already been\nimported from the same path.
Importing WebAssembly modules is supported under the\n--experimental-wasm-modules flag, allowing any .wasm files to be\nimported as normal modules while also supporting their module imports.
--experimental-wasm-modules
.wasm
This integration is in line with the\nES Module Integration Proposal for WebAssembly.
For example, an index.mjs containing:
index.mjs
import * as M from './module.wasm';\nconsole.log(M);\n
executed under:
node --experimental-wasm-modules index.mjs\n
would provide the exports interface for the instantiation of module.wasm.
module.wasm
The await keyword may be used in the top level body of an ECMAScript module.
await
Assuming an a.mjs with
a.mjs
export const five = await Promise.resolve(5);\n
And a b.mjs with
b.mjs
import { five } from './a.mjs';\n\nconsole.log(five); // Logs `5`\n
node b.mjs # works\n
If a top level await expression never resolves, the node process will exit\nwith a 13 status code.
node
13
import { spawn } from 'node:child_process';\nimport { execPath } from 'node:process';\n\nspawn(execPath, [\n '--input-type=module',\n '--eval',\n // Never-resolving Promise:\n 'await new Promise(() => {})',\n]).once('exit', (code) => {\n console.log(code); // Logs `13`\n});\n
Importing network based modules using https: and http: is supported under\nthe --experimental-network-imports flag. This allows web browser-like imports\nto work in Node.js with a few differences due to application stability and\nsecurity concerns that are different when running in a privileged environment\ninstead of a browser sandbox.
https:
http:
--experimental-network-imports
Automatic protocol negotiation for HTTP/2 and HTTP/3 is not yet supported.
http: is vulnerable to man-in-the-middle attacks and is not allowed to be\nused for addresses outside of the IPv4 address 127.0.0.0/8 (127.0.0.1 to\n127.255.255.255) and the IPv6 address ::1. Support for http: is intended\nto be used for local development.
127.0.0.0/8
127.0.0.1
127.255.255.255
::1
Authorization, Cookie, and Proxy-Authorization headers are not sent to the\nserver. Avoid including user info in parts of imported URLs. A security model\nfor safely using these on the server is being worked on.
Authorization
Cookie
Proxy-Authorization
CORS is designed to allow a server to limit the consumers of an API to a\nspecific set of hosts. This is not supported as it does not make sense for a\nserver-based implementation.
These modules cannot access other modules that are not over http: or https:.\nTo still access local modules while avoiding the security concern, pass in\nreferences to the local dependencies:
// file.mjs\nimport worker_threads from 'node:worker_threads';\nimport { configure, resize } from 'https://example.com/imagelib.mjs';\nconfigure({ worker_threads });\n
// https://example.com/imagelib.mjs\nlet worker_threads;\nexport function configure(opts) {\n worker_threads = opts.worker_threads;\n}\nexport function resize(img, size) {\n // Perform resizing in worker_thread to avoid main thread blocking\n}\n
For now, the --experimental-network-imports flag is required to enable loading\nresources over http: or https:. In the future, a different mechanism will be\nused to enforce this. Opt-in is required to prevent transitive dependencies\ninadvertently using potentially mutable state that could affect reliability\nof Node.js applications.
\nThis API is currently being redesigned and will still change.\n
This API is currently being redesigned and will still change.
To customize the default module resolution, loader hooks can optionally be\nprovided via a --experimental-loader ./loader-name.mjs argument to Node.js.
--experimental-loader ./loader-name.mjs
When hooks are used they apply to the entry point and all import calls. They\nwon't apply to require calls; those still follow CommonJS rules.
Loaders follow the pattern of --require:
--require
node \\\n --experimental-loader unpkg \\\n --experimental-loader http-to-https \\\n --experimental-loader cache-buster\n
These are called in the following sequence: cache-buster calls\nhttp-to-https which calls unpkg.
cache-buster
http-to-https
unpkg
Hooks are part of a chain, even if that chain consists of only one custom\n(user-provided) hook and the default hook, which is always present. Hook\nfunctions nest: each one must always return a plain object, and chaining happens\nas a result of each function calling next<hookName>(), which is a reference\nto the subsequent loader’s hook.
next<hookName>()
A hook that returns a value lacking a required property triggers an exception.\nA hook that returns without calling next<hookName>() and without returning\nshortCircuit: true also triggers an exception. These errors are to help\nprevent unintentional breaks in the chain.
shortCircuit: true
\nThe loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.\n
The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
context
conditions
importAssertions
parentURL
nextResolve
resolve
format
'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'
shortCircuit
false
url
The resolve hook chain is responsible for resolving file URL for a given\nmodule specifier and parent URL, and optionally its format (such as 'module')\nas a hint to the load hook. If a format is specified, the load hook is\nultimately responsible for providing the final format value (and it is free to\nignore the hint provided by resolve); if resolve provides a format, a\ncustom load hook is required even if only to pass the value to the Node.js\ndefault load hook.
'module'
load
The module specifier is the string in an import statement or\nimport() expression.
The parent URL is the URL of the module that imported this one, or undefined\nif this is the main entry point for the application.
undefined
The conditions property in context is an array of conditions for\npackage exports conditions that apply to this resolution\nrequest. They can be used for looking up conditional mappings elsewhere or to\nmodify the list when calling the default resolution logic.
The current package exports conditions are always in\nthe context.conditions array passed into the hook. To guarantee default\nNode.js module specifier resolution behavior when calling defaultResolve, the\ncontext.conditions array passed to it must include all elements of the\ncontext.conditions array originally passed into the resolve hook.
context.conditions
defaultResolve
export async function resolve(specifier, context, nextResolve) {\n const { parentURL = null } = context;\n\n if (Math.random() > 0.5) { // Some condition.\n // For some or all specifiers, do some custom logic for resolving.\n // Always return an object of the form {url: <string>}.\n return {\n shortCircuit: true,\n url: parentURL ?\n new URL(specifier, parentURL).href :\n new URL(specifier).href,\n };\n }\n\n if (Math.random() < 0.5) { // Another condition.\n // When calling `defaultResolve`, the arguments can be modified. In this\n // case it's adding another value for matching conditional exports.\n return nextResolve(specifier, {\n ...context,\n conditions: [...context.conditions, 'another-condition'],\n });\n }\n\n // Defer to the next hook in the chain, which would be the\n // Node.js default resolve if this is the last user-specified loader.\n return nextResolve(specifier);\n}\n
\nIn a previous version of this API, this was split across 3 separate, now\ndeprecated, hooks (getFormat, getSource, and transformSource).\n
In a previous version of this API, this was split across 3 separate, now\ndeprecated, hooks (getFormat, getSource, and transformSource).
getFormat
getSource
transformSource
nextLoad
source
The load hook provides a way to define a custom method of determining how\na URL should be interpreted, retrieved, and parsed. It is also in charge of\nvalidating the import assertion.
The final value of format must be one of the following:
'builtin'
'commonjs'
string
ArrayBuffer
TypedArray
'wasm'
The value of source is ignored for type 'builtin' because currently it is\nnot possible to replace the value of a Node.js builtin (core) module. The value\nof source is ignored for type 'commonjs' because the CommonJS module loader\ndoes not provide a mechanism for the ES module loader to override the\nCommonJS module return value. This limitation might be\novercome in the future.
\nCaveat: The ESM load hook and namespaced exports from CommonJS modules\nare incompatible. Attempting to use them together will result in an empty\nobject from the import. This may be addressed in the future.\n
Caveat: The ESM load hook and namespaced exports from CommonJS modules\nare incompatible. Attempting to use them together will result in an empty\nobject from the import. This may be addressed in the future.
\nThese types all correspond to classes defined in ECMAScript.\n
These types all correspond to classes defined in ECMAScript.
SharedArrayBuffer
Uint8Array
If the source value of a text-based format (i.e., 'json', 'module')\nis not a string, it is converted to a string using util.TextDecoder.
util.TextDecoder
The load hook provides a way to define a custom method for retrieving the\nsource code of an ES module specifier. This would allow a loader to potentially\navoid reading files from disk. It could also be used to map an unrecognized\nformat to a supported one, for example yaml to module.
yaml
module
export async function load(url, context, nextLoad) {\n const { format } = context;\n\n if (Math.random() > 0.5) { // Some condition\n /*\n For some or all URLs, do some custom logic for retrieving the source.\n Always return an object of the form {\n format: <string>,\n source: <string|buffer>,\n }.\n */\n return {\n format,\n shortCircuit: true,\n source: '...',\n };\n }\n\n // Defer to the next hook in the chain.\n return nextLoad(url);\n}\n
In a more advanced scenario, this can also be used to transform an unsupported\nsource to a supported one (see Examples below).
\nIn a previous version of this API, this hook was named\ngetGlobalPreloadCode.\n
In a previous version of this API, this hook was named\ngetGlobalPreloadCode.
getGlobalPreloadCode
port
Sometimes it might be necessary to run some code inside of the same global\nscope that the application runs in. This hook allows the return of a string\nthat is run as a sloppy-mode script on startup.
Similar to how CommonJS wrappers work, the code runs in an implicit function\nscope. The only argument is a require-like function that can be used to load\nbuiltins like \"fs\": getBuiltin(request: string).
getBuiltin(request: string)
If the code needs more advanced require features, it has to construct\nits own require using module.createRequire().
export function globalPreload(context) {\n return `\\\nglobalThis.someInjectedProperty = 42;\nconsole.log('I just set some globals!');\n\nconst { createRequire } = getBuiltin('module');\nconst { cwd } = getBuiltin('process');\n\nconst require = createRequire(cwd() + '/<preload>');\n// [...]\n`;\n}\n
In order to allow communication between the application and the loader, another\nargument is provided to the preload code: port. This is available as a\nparameter to the loader hook and inside of the source text returned by the hook.\nSome care must be taken in order to properly call port.ref() and\nport.unref() to prevent a process from being in a state where it won't\nclose normally.
port.ref()
port.unref()
/**\n * This example has the application context send a message to the loader\n * and sends the message back to the application context\n */\nexport function globalPreload({ port }) {\n port.onmessage = (evt) => {\n port.postMessage(evt.data);\n };\n return `\\\n port.postMessage('console.log(\"I went to the Loader and back\");');\n port.onmessage = (evt) => {\n eval(evt.data);\n };\n `;\n}\n
The various loader hooks can be used together to accomplish wide-ranging\ncustomizations of the Node.js code loading and evaluation behaviors.
In current Node.js, specifiers starting with https:// are experimental (see\nHTTPS and HTTP imports).
https://
The loader below registers hooks to enable rudimentary support for such\nspecifiers. While this may seem like a significant improvement to Node.js core\nfunctionality, there are substantial downsides to actually using this loader:\nperformance is much slower than loading files from disk, there is no caching,\nand there is no security.
// https-loader.mjs\nimport { get } from 'node:https';\n\nexport function resolve(specifier, context, nextResolve) {\n const { parentURL = null } = context;\n\n // Normally Node.js would error on specifiers starting with 'https://', so\n // this hook intercepts them and converts them into absolute URLs to be\n // passed along to the later hooks below.\n if (specifier.startsWith('https://')) {\n return {\n shortCircuit: true,\n url: specifier\n };\n } else if (parentURL && parentURL.startsWith('https://')) {\n return {\n shortCircuit: true,\n url: new URL(specifier, parentURL).href,\n };\n }\n\n // Let Node.js handle all other specifiers.\n return nextResolve(specifier);\n}\n\nexport function load(url, context, nextLoad) {\n // For JavaScript to be loaded over the network, we need to fetch and\n // return it.\n if (url.startsWith('https://')) {\n return new Promise((resolve, reject) => {\n get(url, (res) => {\n let data = '';\n res.on('data', (chunk) => data += chunk);\n res.on('end', () => resolve({\n // This example assumes all network-provided JavaScript is ES module\n // code.\n format: 'module',\n shortCircuit: true,\n source: data,\n }));\n }).on('error', (err) => reject(err));\n });\n }\n\n // Let Node.js handle all other URLs.\n return nextLoad(url);\n}\n
// main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n
With the preceding loader, running\nnode --experimental-loader ./https-loader.mjs ./main.mjs\nprints the current version of CoffeeScript per the module at the URL in\nmain.mjs.
node --experimental-loader ./https-loader.mjs ./main.mjs
main.mjs
Sources that are in formats Node.js doesn't understand can be converted into\nJavaScript using the load hook. Before that hook gets called,\nhowever, a resolve hook needs to tell Node.js not to\nthrow an error on unknown file types.
This is less performant than transpiling source files before running\nNode.js; a transpiler loader should only be used for development and testing\npurposes.
// coffeescript-loader.mjs\nimport { readFile } from 'node:fs/promises';\nimport { dirname, extname, resolve as resolvePath } from 'node:path';\nimport { cwd } from 'node:process';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport CoffeeScript from 'coffeescript';\n\nconst baseURL = pathToFileURL(`${cwd()}/`).href;\n\n// CoffeeScript files end in .coffee, .litcoffee, or .coffee.md.\nconst extensionsRegex = /\\.coffee$|\\.litcoffee$|\\.coffee\\.md$/;\n\nexport async function resolve(specifier, context, nextResolve) {\n if (extensionsRegex.test(specifier)) {\n const { parentURL = baseURL } = context;\n\n // Node.js normally errors on unknown file extensions, so return a URL for\n // specifiers ending in the CoffeeScript file extensions.\n return {\n shortCircuit: true,\n url: new URL(specifier, parentURL).href\n };\n }\n\n // Let Node.js handle all other specifiers.\n return nextResolve(specifier);\n}\n\nexport async function load(url, context, nextLoad) {\n if (extensionsRegex.test(url)) {\n // Now that we patched resolve to let CoffeeScript URLs through, we need to\n // tell Node.js what format such URLs should be interpreted as. Because\n // CoffeeScript transpiles into JavaScript, it should be one of the two\n // JavaScript formats: 'commonjs' or 'module'.\n\n // CoffeeScript files can be either CommonJS or ES modules, so we want any\n // CoffeeScript file to be treated by Node.js the same as a .js file at the\n // same location. To determine how Node.js would interpret an arbitrary .js\n // file, search up the file system for the nearest parent package.json file\n // and read its \"type\" field.\n const format = await getPackageType(url);\n // When a hook returns a format of 'commonjs', `source` is be ignored.\n // To handle CommonJS files, a handler needs to be registered with\n // `require.extensions` in order to process the files with the CommonJS\n // loader. Avoiding the need for a separate CommonJS handler is a future\n // enhancement planned for ES module loaders.\n if (format === 'commonjs') {\n return {\n format,\n shortCircuit: true,\n };\n }\n\n const { source: rawSource } = await nextLoad(url, { ...context, format });\n // This hook converts CoffeeScript source code into JavaScript source code\n // for all imported CoffeeScript files.\n const transformedSource = coffeeCompile(rawSource.toString(), url);\n\n return {\n format,\n shortCircuit: true,\n source: transformedSource,\n };\n }\n\n // Let Node.js handle all other URLs.\n return nextLoad(url);\n}\n\nasync function getPackageType(url) {\n // `url` is only a file path during the first iteration when passed the\n // resolved url from the load() hook\n // an actual file path from load() will contain a file extension as it's\n // required by the spec\n // this simple truthy check for whether `url` contains a file extension will\n // work for most projects but does not cover some edge-cases (such as\n // extensionless files or a url ending in a trailing space)\n const isFilePath = !!extname(url);\n // If it is a file path, get the directory it's in\n const dir = isFilePath ?\n dirname(fileURLToPath(url)) :\n url;\n // Compose a file path to a package.json in the same directory,\n // which may or may not exist\n const packagePath = resolvePath(dir, 'package.json');\n // Try to read the possibly nonexistent package.json\n const type = await readFile(packagePath, { encoding: 'utf8' })\n .then((filestring) => JSON.parse(filestring).type)\n .catch((err) => {\n if (err?.code !== 'ENOENT') console.error(err);\n });\n // Ff package.json existed and contained a `type` field with a value, voila\n if (type) return type;\n // Otherwise, (if not at the root) continue checking the next directory up\n // If at the root, stop and return false\n return dir.length > 1 && getPackageType(resolvePath(dir, '..'));\n}\n
# main.coffee\nimport { scream } from './scream.coffee'\nconsole.log scream 'hello, world'\n\nimport { version } from 'node:process'\nconsole.log \"Brought to you by Node.js version #{version}\"\n
# scream.coffee\nexport scream = (str) -> str.toUpperCase()\n
With the preceding loader, running\nnode --experimental-loader ./coffeescript-loader.mjs main.coffee\ncauses main.coffee to be turned into JavaScript after its source code is\nloaded from disk but before Node.js executes it; and so on for any .coffee,\n.litcoffee or .coffee.md files referenced via import statements of any\nloaded file.
node --experimental-loader ./coffeescript-loader.mjs main.coffee
main.coffee
.coffee
.litcoffee
.coffee.md
The resolver has the following properties:
The algorithm to load an ES module specifier is given through the\nESM_RESOLVE method below. It returns the resolved URL for a\nmodule specifier relative to a parentURL.
The algorithm to determine the module format of a resolved URL is\nprovided by ESM_FORMAT, which returns the unique module\nformat for any file. The \"module\" format is returned for an ECMAScript\nModule, while the \"commonjs\" format is used to indicate loading through the\nlegacy CommonJS loader. Additional formats such as \"addon\" can be extended in\nfuture updates.
In the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.
defaultConditions is the conditional environment name array,\n[\"node\", \"import\"].
[\"node\", \"import\"]
The resolver can throw the following errors:
ESM_RESOLVE(specifier, parentURL)
\n\nLet resolved be undefined.\nIf specifier is a valid URL, then\n\nSet resolved to the result of parsing and reserializing\nspecifier as a URL.\n\n\nOtherwise, if specifier starts with \"/\", \"./\", or \"../\", then\n\nSet resolved to the URL resolution of specifier relative to\nparentURL.\n\n\nOtherwise, if specifier starts with \"#\", then\n\nSet resolved to the destructured value of the result of\nPACKAGE_IMPORTS_RESOLVE(specifier, parentURL,\ndefaultConditions).\n\n\nOtherwise,\n\nNote: specifier is now a bare specifier.\nSet resolved the result of\nPACKAGE_RESOLVE(specifier, parentURL).\n\n\nLet format be undefined.\nIf resolved is a \"file:\" URL, then\n\nIf resolved contains any percent encodings of \"/\" or \"\\\" (\"%2F\"\nand \"%5C\" respectively), then\n\nThrow an Invalid Module Specifier error.\n\n\nIf the file at resolved is a directory, then\n\nThrow an Unsupported Directory Import error.\n\n\nIf the file at resolved does not exist, then\n\nThrow a Module Not Found error.\n\n\nSet resolved to the real path of resolved, maintaining the\nsame URL querystring and fragment components.\nSet format to the result of ESM_FILE_FORMAT(resolved).\n\n\nOtherwise,\n\nSet format the module format of the content type associated with the\nURL resolved.\n\n\nLoad resolved as module format, format.\n\n
PACKAGE_RESOLVE(packageSpecifier, parentURL)
\n\nLet packageName be undefined.\nIf packageSpecifier is an empty string, then\n\nThrow an Invalid Module Specifier error.\n\n\nIf packageSpecifier is a Node.js builtin module name, then\n\nReturn the string \"node:\" concatenated with packageSpecifier.\n\n\nIf packageSpecifier does not start with \"@\", then\n\nSet packageName to the substring of packageSpecifier until the first\n\"/\" separator or the end of the string.\n\n\nOtherwise,\n\nIf packageSpecifier does not contain a \"/\" separator, then\n\nThrow an Invalid Module Specifier error.\n\n\nSet packageName to the substring of packageSpecifier\nuntil the second \"/\" separator or the end of the string.\n\n\nIf packageName starts with \".\" or contains \"\\\" or \"%\", then\n\nThrow an Invalid Module Specifier error.\n\n\nLet packageSubpath be \".\" concatenated with the substring of\npackageSpecifier from the position at the length of packageName.\nIf packageSubpath ends in \"/\", then\n\nThrow an Invalid Module Specifier error.\n\n\nLet selfUrl be the result of\nPACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).\nIf selfUrl is not undefined, return selfUrl.\nWhile parentURL is not the file system root,\n\nLet packageURL be the URL resolution of \"node_modules/\"\nconcatenated with packageSpecifier, relative to parentURL.\nSet parentURL to the parent folder URL of parentURL.\nIf the folder at packageURL does not exist, then\n\nContinue the next loop iteration.\n\n\nLet pjson be the result of READ_PACKAGE_JSON(packageURL).\nIf pjson is not null and pjson.exports is not null or\nundefined, then\n\nReturn the result of PACKAGE_EXPORTS_RESOLVE(packageURL,\npackageSubpath, pjson.exports, defaultConditions).\n\n\nOtherwise, if packageSubpath is equal to \".\", then\n\nIf pjson.main is a string, then\n\nReturn the URL resolution of main in packageURL.\n\n\n\n\nOtherwise,\n\nReturn the URL resolution of packageSubpath in packageURL.\n\n\n\n\nThrow a Module Not Found error.\n\n
PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)
\n\nLet packageURL be the result of LOOKUP_PACKAGE_SCOPE(parentURL).\nIf packageURL is null, then\n\nReturn undefined.\n\n\nLet pjson be the result of READ_PACKAGE_JSON(packageURL).\nIf pjson is null or if pjson.exports is null or\nundefined, then\n\nReturn undefined.\n\n\nIf pjson.name is equal to packageName, then\n\nReturn the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath,\npjson.exports, defaultConditions).\n\n\nOtherwise, return undefined.\n\n
PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)
\n\nIf exports is an Object with both a key starting with \".\" and a key not\nstarting with \".\", throw an Invalid Package Configuration error.\nIf subpath is equal to \".\", then\n\nLet mainExport be undefined.\nIf exports is a String or Array, or an Object containing no keys\nstarting with \".\", then\n\nSet mainExport to exports.\n\n\nOtherwise if exports is an Object containing a \".\" property, then\n\nSet mainExport to exports[\".\"].\n\n\nIf mainExport is not undefined, then\n\nLet resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, \"\", false, false,\nconditions).\nIf resolved is not null or undefined, then\n\nReturn resolved.\n\n\n\n\n\n\nOtherwise, if exports is an Object and all keys of exports start with\n\".\", then\n\nLet matchKey be the string \"./\" concatenated with subpath.\nLet resolvedMatch be result of PACKAGE_IMPORTS_EXPORTS_RESOLVE(\nmatchKey, exports, packageURL, false, conditions).\nIf resolvedMatch.resolve is not null or undefined, then\n\nReturn resolvedMatch.\n\n\n\n\nThrow a Package Path Not Exported error.\n\n
PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)
\n\nAssert: specifier begins with \"#\".\nIf specifier is exactly equal to \"#\" or starts with \"#/\", then\n\nThrow an Invalid Module Specifier error.\n\n\nLet packageURL be the result of LOOKUP_PACKAGE_SCOPE(parentURL).\nIf packageURL is not null, then\n\nLet pjson be the result of READ_PACKAGE_JSON(packageURL).\nIf pjson.imports is a non-null Object, then\n\nLet resolvedMatch be the result of\nPACKAGE_IMPORTS_EXPORTS_RESOLVE(specifier, pjson.imports,\npackageURL, true, conditions).\nIf resolvedMatch.resolve is not null or undefined, then\n\nReturn resolvedMatch.\n\n\n\n\n\n\nThrow a Package Import Not Defined error.\n\n
PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL,\nisImports, conditions)
\n\nIf matchKey is a key of matchObj and does not end in \"/\" or contain\n\"*\", then\n\nLet target be the value of matchObj[matchKey].\nLet resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, \"\", false, isImports, conditions).\nReturn the object { resolved, exact: true }.\n\n\nLet expansionKeys be the list of keys of matchObj either ending in\n\"/\" or containing only a single \"*\", sorted by the sorting function\nPATTERN_KEY_COMPARE which orders in descending order of specificity.\nFor each key expansionKey in expansionKeys, do\n\nLet patternBase be null.\nIf expansionKey contains \"*\", set patternBase to the substring of\nexpansionKey up to but excluding the first \"*\" character.\nIf patternBase is not null and matchKey starts with but is not\nequal to patternBase, then\n\nIf matchKey ends with \"/\", throw an Invalid Module Specifier\nerror.\nLet patternTrailer be the substring of expansionKey from the\nindex after the first \"*\" character.\nIf patternTrailer has zero length, or if matchKey ends with\npatternTrailer and the length of matchKey is greater than or\nequal to the length of expansionKey, then\n\nLet target be the value of matchObj[expansionKey].\nLet subpath be the substring of matchKey starting at the\nindex of the length of patternBase up to the length of\nmatchKey minus the length of patternTrailer.\nLet resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, true, isImports,\nconditions).\nReturn the object { resolved, exact: true }.\n\n\n\n\nOtherwise if patternBase is null and matchKey starts with\nexpansionKey, then\n\nLet target be the value of matchObj[expansionKey].\nLet subpath be the substring of matchKey starting at the\nindex of the length of expansionKey.\nLet resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, false, isImports,\nconditions).\nReturn the object { resolved, exact: false }.\n\n\n\n\nReturn the object { resolved: null, exact: true }.\n\n
PATTERN_KEY_COMPARE(keyA, keyB)
\n\nAssert: keyA ends with \"/\" or contains only a single \"*\".\nAssert: keyB ends with \"/\" or contains only a single \"*\".\nLet baseLengthA be the index of \"*\" in keyA plus one, if keyA\ncontains \"*\", or the length of keyA otherwise.\nLet baseLengthB be the index of \"*\" in keyB plus one, if keyB\ncontains \"*\", or the length of keyB otherwise.\nIf baseLengthA is greater than baseLengthB, return -1.\nIf baseLengthB is greater than baseLengthA, return 1.\nIf keyA does not contain \"*\", return 1.\nIf keyB does not contain \"*\", return -1.\nIf the length of keyA is greater than the length of keyB, return -1.\nIf the length of keyB is greater than the length of keyA, return 1.\nReturn 0.\n\n
PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, pattern,\ninternal, conditions)
\n\nIf target is a String, then\n\nIf pattern is false, subpath has non-zero length and target\ndoes not end with \"/\", throw an Invalid Module Specifier error.\nIf target does not start with \"./\", then\n\nIf internal is true and target does not start with \"../\" or\n\"/\" and is not a valid URL, then\n\nIf pattern is true, then\n\nReturn PACKAGE_RESOLVE(target with every instance of\n\"*\" replaced by subpath, packageURL + \"/\").\n\n\nReturn PACKAGE_RESOLVE(target + subpath,\npackageURL + \"/\").\n\n\nOtherwise, throw an Invalid Package Target error.\n\n\nIf target split on \"/\" or \"\\\" contains any \".\", \"..\", or\n\"node_modules\" segments after the first segment, case insensitive and\nincluding percent encoded variants, throw an Invalid Package Target\nerror.\nLet resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.\nAssert: resolvedTarget is contained in packageURL.\nIf subpath split on \"/\" or \"\\\" contains any \".\", \"..\", or\n\"node_modules\" segments, case insensitive and including percent\nencoded variants, throw an Invalid Module Specifier error.\nIf pattern is true, then\n\nReturn the URL resolution of resolvedTarget with every instance of\n\"*\" replaced with subpath.\n\n\nOtherwise,\n\nReturn the URL resolution of the concatenation of subpath and\nresolvedTarget.\n\n\n\n\nOtherwise, if target is a non-null Object, then\n\nIf exports contains any index property keys, as defined in ECMA-262\n6.1.7 Array Index, throw an Invalid Package Configuration error.\nFor each property p of target, in object insertion order as,\n\nIf p equals \"default\" or conditions contains an entry for p,\nthen\n\nLet targetValue be the value of the p property in target.\nLet resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions).\nIf resolved is equal to undefined, continue the loop.\nReturn resolved.\n\n\n\n\nReturn undefined.\n\n\nOtherwise, if target is an Array, then\n\nIf _target.length is zero, return null.\nFor each item targetValue in target, do\n\nLet resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions), continuing the loop on any Invalid Package Target\nerror.\nIf resolved is undefined, continue the loop.\nReturn resolved.\n\n\nReturn or throw the last fallback resolution null return or error.\n\n\nOtherwise, if target is null, return null.\nOtherwise throw an Invalid Package Target error.\n\n
ESM_FILE_FORMAT(url)
\n\nAssert: url corresponds to an existing file.\nIf url ends in \".mjs\", then\n\nReturn \"module\".\n\n\nIf url ends in \".cjs\", then\n\nReturn \"commonjs\".\n\n\nIf url ends in \".json\", then\n\nReturn \"json\".\n\n\nLet packageURL be the result of LOOKUP_PACKAGE_SCOPE(url).\nLet pjson be the result of READ_PACKAGE_JSON(packageURL).\nIf pjson?.type exists and is \"module\", then\n\nIf url ends in \".js\", then\n\nReturn \"module\".\n\n\nThrow an Unsupported File Extension error.\n\n\nOtherwise,\n\nThrow an Unsupported File Extension error.\n\n\n\n
LOOKUP_PACKAGE_SCOPE(url)
\n\nLet scopeURL be url.\nWhile scopeURL is not the file system root,\n\nSet scopeURL to the parent URL of scopeURL.\nIf scopeURL ends in a \"node_modules\" path segment, return null.\nLet pjsonURL be the resolution of \"package.json\" within\nscopeURL.\nif the file at pjsonURL exists, then\n\nReturn scopeURL.\n\n\n\n\nReturn null.\n\n
READ_PACKAGE_JSON(packageURL)
\n\nLet pjsonURL be the resolution of \"package.json\" within packageURL.\nIf the file at pjsonURL does not exist, then\n\nReturn null.\n\n\nIf the file at packageURL does not parse as valid JSON, then\n\nThrow an Invalid Package Configuration error.\n\n\nReturn the parsed JSON source of the file at pjsonURL.\n\n
\nDo not rely on this flag. We plan to remove it once the\nLoaders API has advanced to the point that equivalent functionality can\nbe achieved via custom loaders.\n
Do not rely on this flag. We plan to remove it once the\nLoaders API has advanced to the point that equivalent functionality can\nbe achieved via custom loaders.
The current specifier resolution does not support all default behavior of\nthe CommonJS loader. One of the behavior differences is automatic resolution\nof file extensions and the ability to import directories that have an index\nfile.
The --experimental-specifier-resolution=[mode] flag can be used to customize\nthe extension resolution algorithm. The default mode is explicit, which\nrequires the full path to a module be provided to the loader. To enable the\nautomatic extension resolution and importing from directories that include an\nindex file use the node mode.
--experimental-specifier-resolution=[mode]
explicit
$ node index.mjs\nsuccess!\n$ node index # Failure!\nError: Cannot find module\n$ node --experimental-specifier-resolution=node index\nsuccess!\n