{ "type": "module", "source": "doc/api/esm.md", "introduced_in": "v8.5.0", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": [ "v12.22.0" ], "pr-url": "https://github.com/nodejs/node/pull/35781", "description": "Stabilize modules implementation." }, { "version": [ "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/35249", "description": "Support for detection of CommonJS named exports." }, { "version": "v12.20.0", "pr-url": "https://github.com/nodejs/node/pull/31974", "description": "Remove experimental modules warning." }, { "version": [ "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/29866", "description": "Loading ECMAScript modules no longer requires a command-line flag." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26745", "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." } ] }, "stability": 2, "stabilityText": "Stable", "properties": [ { "textRaw": "`meta` {Object}", "type": "Object", "name": "meta", "desc": "
The import.meta
metaproperty is an Object
that contains the following\nproperty:
url
<string> The absolute file:
URL of the module.ECMAScript modules are the official standard format to package JavaScript\ncode for reuse. Modules are defined using a variety of import
and\nexport
statements.
The following example of an ES module exports a function:
\n// addTwo.mjs\nfunction addTwo(num) {\n return num + 2;\n}\n\nexport { addTwo };\n
\nThe following example of an ES module imports the function from addTwo.mjs
:
// app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));\n
\nNode.js fully supports ECMAScript modules as they are currently specified and\nprovides interoperability between them and its original module format,\nCommonJS.
\n\n\n\n
", "type": "misc", "displayName": "esm" }, { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "Node.js treats JavaScript code as CommonJS modules by default.\nAuthors can tell Node.js to treat JavaScript code as ECMAScript modules\nvia the .mjs
file extension, the package.json
\"type\"
field, or the\n--input-type
flag. See\nModules: Packages for more\ndetails.
\n\n\n\n\n\n\n\n\n\n\n\n\n
" }, { "textRaw": "Packages", "name": "packages", "desc": "This section was moved to Modules: Packages.
", "type": "misc", "displayName": "Packages" }, { "textRaw": "`import` Specifiers", "name": "`import`_specifiers", "modules": [ { "textRaw": "Terminology", "name": "terminology", "desc": "The specifier of an import
statement is the string after the from
keyword,\ne.g. 'path'
in import { sep } from 'path'
. Specifiers are also used in\nexport from
statements, and as the argument to an import()
expression.
There are four types of specifiers:
\nBare specifiers like 'some-package'
. They refer to an entry point of a\npackage by the package name.
Deep import specifiers like 'some-package/lib/shuffle.mjs'
. They refer to\na path within a package prefixed by the package name.
Relative specifiers like './startup.js'
or '../config.mjs'
. They refer\nto a path relative to the location of the importing file.
Absolute specifiers like 'file:///opt/nodejs/config.js'
. They refer\ndirectly and explicitly to a full path.
Bare specifiers, and the bare specifier portion of deep import specifiers, are\nstrings; but everything else in a specifier is a URL.
\nfile:
, node:
, and data:
URLs are supported. A specifier like\n'https://example.com/app.js'
may be supported by browsers but it is not\nsupported in Node.js.
Specifiers may not begin with /
or //
. These are reserved for potential\nfuture use. The root of the current volume may be referenced via file:///
.
node:
URLs are supported as a means to load Node.js builtin modules. This\nURL scheme allows for builtin modules to be referenced by valid absolute URL\nstrings.
import fs from 'node:fs/promises';\n
",
"type": "module",
"displayName": "`node:` Imports"
},
{
"textRaw": "`data:` Imports",
"name": "`data:`_imports",
"meta": {
"added": [
"v12.10.0"
],
"changes": []
},
"desc": "data:
URLs are supported for importing with the following MIME types:
text/javascript
for ES Modulesapplication/json
for JSONapplication/wasm
for Wasmdata:
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. An example of a data:
\nURLs being used is:
import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"';\n
",
"type": "module",
"displayName": "`data:` Imports"
}
],
"type": "module",
"displayName": "Terminology"
}
],
"type": "misc",
"displayName": "`import` Specifiers"
},
{
"textRaw": "Differences between ES modules and CommonJS",
"name": "differences_between_es_modules_and_commonjs",
"modules": [
{
"textRaw": "Mandatory file extensions",
"name": "mandatory_file_extensions",
"desc": "A file extension must be provided when using the import
keyword. Directory\nindexes (e.g. './startup/index.js'
) must also be fully specified.
This behavior matches how import
behaves in browser environments, assuming a\ntypically configured server.
NODE_PATH
is not part of resolving import
specifiers. Please use symlinks\nif this behavior is desired.
These CommonJS variables are not available in ES modules.
\nrequire
can be imported into an ES module using module.createRequire()
.
Equivalents of __filename
and __dirname
can be created inside of each file\nvia import.meta.url
.
import { fileURLToPath } from 'url';\nimport { dirname } from 'path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n
",
"type": "module",
"displayName": "No `require`, `exports`, `module.exports`, `__filename`, `__dirname`"
},
{
"textRaw": "No `require.resolve`",
"name": "no_`require.resolve`",
"desc": "Former use cases relying on require.resolve
to determine the resolved path\nof a module can be supported via import.meta.resolve
, which is experimental\nand supported via the --experimental-import-meta-resolve
flag:
(async () => {\n const dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n})();\n
\nimport.meta.resolve
also accepts a second argument which is the parent module\nfrom which to resolve from:
(async () => {\n // Equivalent to import.meta.resolve('./dep')\n await import.meta.resolve('./dep', import.meta.url);\n})();\n
\nThis function is asynchronous because the ES module resolver in Node.js is\nasynchronous. With the introduction of Top-Level Await, these use cases\nwill be easier as they won't require an async function wrapper.
", "type": "module", "displayName": "No `require.resolve`" }, { "textRaw": "No `require.extensions`", "name": "no_`require.extensions`", "desc": "require.extensions
is not used by import
. The expectation is that loader\nhooks can provide this workflow in the future.
require.cache
is not used by import
. It has a separate cache.
ES modules are resolved and cached based upon\nURL semantics. This means that files containing\nspecial characters such as #
and ?
need to be escaped.
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
\nFor now, only modules using the file:
protocol can be loaded.
require
always treats the files it references as CommonJS. This applies\nwhether require
is used the traditional way within a CommonJS environment, or\nin an ES module environment using module.createRequire()
.
To include an ES module into CommonJS, use import()
.
An import
statement can reference an ES module or a CommonJS module.\nimport
statements are permitted only in ES modules. For similar functionality\nin CommonJS, see import()
.
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.
Additional experimental flags are available for importing\nWasm modules or\nJSON modules. For importing native modules or\nJSON modules unflagged, see module.createRequire()
.
The specifier of an import
statement (the string after the from
keyword)\ncan either be an URL-style relative path like './file.mjs'
or a package name\nlike 'fs'
.
Like in CommonJS, files within packages can be accessed by appending a path to\nthe package name; unless the package’s package.json
contains an\n\"exports\"
field, in which case files within packages need to be accessed\nvia the path defined in \"exports\"
.
import { sin, cos } from 'geometry/trigonometry-functions.mjs';\n
",
"type": "module",
"displayName": "`import` statements"
},
{
"textRaw": "`import()` expressions",
"name": "`import()`_expressions",
"desc": "Dynamic import()
is supported in both CommonJS and ES modules. It can be\nused to include ES module files from CommonJS code.
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:
\n\nimport { 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
\nThe ECMAScript Module Namespace representation of a CommonJS module is always\na namespace with a default
export key pointing to the CommonJS\nmodule.exports
value.
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';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n// [Module] { default: <module.exports> }\n// true\n
\nFor 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.
\nFor example, consider a CommonJS module written:
\n// cjs.cjs\nexports.name = 'exported';\n
\nThe preceding module supports named imports in ES modules:
\n\nimport { 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
\nAs 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.
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.
\nNamed exports detection covers many common export patterns, reexport patterns\nand build tool and transpiler outputs. See cjs-module-lexer for the exact\nsemantics implemented.
", "type": "misc", "displayName": "CommonJS Namespaces" }, { "textRaw": "Builtin modules", "name": "builtin_modules", "desc": "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()
.
import EventEmitter from 'events';\nconst e = new EventEmitter();\n
\nimport { readFile } from 'fs';\nreadFile('./foo.txt', (err, source) => {\n if (err) {\n console.error(err);\n } else {\n console.log(source);\n }\n});\n
\nimport fs, { readFileSync } from 'fs';\nimport { syncBuiltinESMExports } from 'module';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;\n
",
"type": "misc",
"displayName": "Builtin modules"
},
{
"textRaw": "CommonJS, JSON, and native modules",
"name": "commonjs,_json,_and_native_modules",
"desc": "CommonJS, JSON, and native modules can be used with\nmodule.createRequire()
.
// cjs.cjs\nmodule.exports = 'cjs';\n\n// esm.mjs\nimport { createRequire } from 'module';\n\nconst require = createRequire(import.meta.url);\n\nconst cjs = require('./cjs.cjs');\ncjs === 'cjs'; // true\n
",
"type": "misc",
"displayName": "CommonJS, JSON, and native modules"
},
{
"textRaw": "Experimental JSON modules",
"name": "experimental_json_modules",
"desc": "Currently importing JSON modules are only supported in the commonjs
mode\nand are loaded using the CJS loader. WHATWG JSON modules specification are\nstill being standardized, and are experimentally supported by including the\nadditional flag --experimental-json-modules
when running Node.js.
When the --experimental-json-modules
flag is included, both the\ncommonjs
and module
mode use the new experimental JSON\nloader. The imported JSON only exposes a default
. There is no\nsupport for named exports. A cache entry is created in the CommonJS\ncache to avoid duplication. The same object is returned in\nCommonJS if the JSON module has already been imported from the\nsame path.
Assuming an index.mjs
with
import packageConfig from './package.json';\n
\nThe --experimental-json-modules
flag is needed for the module\nto work.
node index.mjs # fails\nnode --experimental-json-modules index.mjs # works\n
",
"type": "misc",
"displayName": "Experimental JSON modules"
},
{
"textRaw": "Experimental Wasm modules",
"name": "experimental_wasm_modules",
"desc": "Importing Web Assembly 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.
This integration is in line with the\nES Module Integration Proposal for Web Assembly.
\nFor example, an index.mjs
containing:
import * as M from './module.wasm';\nconsole.log(M);\n
\nexecuted under:
\nnode --experimental-wasm-modules index.mjs\n
\nwould provide the exports interface for the instantiation of module.wasm
.
Note: This API is currently being redesigned and will still change.
\nTo customize the default module resolution, loader hooks can optionally be\nprovided via a --experimental-loader ./loader-name.mjs
argument to Node.js.
When hooks are used they only apply to ES module loading and not to any\nCommonJS modules loaded.
", "miscs": [ { "textRaw": "Hooks", "name": "hooks", "methods": [ { "textRaw": "`resolve(specifier, context, defaultResolve)`", "type": "method", "name": "resolve", "signatures": [ { "params": [] } ], "desc": "\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
specifier
<string>context
<Object>\nconditions
<string[]>parentURL
<string>defaultResolve
<Function>url
<string>The resolve
hook returns the resolved file URL for a given module specifier\nand parent URL. The module specifier is the string in an import
statement or\nimport()
expression, and the parent URL is the URL of the module that imported\nthis one, or undefined
if this is the main entry point for the application.
The conditions
property on the context
is an array of conditions for\nConditional exports that apply to this resolution request. They can be used\nfor looking up conditional mappings elsewhere or to modify the list when calling\nthe 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.
/**\n * @param {string} specifier\n * @param {{\n * conditions: !Array<string>,\n * parentURL: !(string | undefined),\n * }} context\n * @param {Function} defaultResolve\n * @returns {Promise<{ url: string }>}\n */\nexport async function resolve(specifier, context, defaultResolve) {\n const { parentURL = null } = context;\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 url: parentURL ?\n new URL(specifier, parentURL).href :\n new URL(specifier).href,\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 defaultResolve(specifier, {\n ...context,\n conditions: [...context.conditions, 'another-condition'],\n });\n }\n // Defer to Node.js for all other specifiers.\n return defaultResolve(specifier, context, defaultResolve);\n}\n
"
},
{
"textRaw": "`getFormat(url, context, defaultGetFormat)`",
"type": "method",
"name": "getFormat",
"signatures": [
{
"params": []
}
],
"desc": "\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
url
<string>context
<Object>defaultGetFormat
<Function>format
<string>The getFormat
hook provides a way to define a custom method of determining how\na URL should be interpreted. The format
returned also affects what the\nacceptable forms of source values are for a module when parsing. This can be one\nof the following:
format | \nDescription | \nAcceptable Types For source Returned by getSource or transformSource | \n
---|---|---|
'builtin' | \nLoad a Node.js builtin module | \nNot applicable | \n
'dynamic' | \nUse a dynamic instantiate hook | \nNot applicable | \n
'commonjs' | \nLoad a Node.js CommonJS module | \nNot applicable | \n
'json' | \nLoad a JSON file | \n{ string , ArrayBuffer , TypedArray } | \n
'module' | \nLoad an ES module | \n{ string , ArrayBuffer , TypedArray } | \n
'wasm' | \nLoad a WebAssembly module | \n{ ArrayBuffer , TypedArray } | \n
Note: These types all correspond to classes defined in ECMAScript.
\nArrayBuffer
object is a SharedArrayBuffer
.TypedArray
object is a Uint8Array
.Note: If the source value of a text-based format (i.e., 'json'
, 'module'
) is\nnot a string, it is converted to a string using util.TextDecoder
.
/**\n * @param {string} url\n * @param {Object} context (currently empty)\n * @param {Function} defaultGetFormat\n * @returns {Promise<{ format: string }>}\n */\nexport async function getFormat(url, context, defaultGetFormat) {\n if (Math.random() > 0.5) { // Some condition.\n // For some or all URLs, do some custom logic for determining format.\n // Always return an object of the form {format: <string>}, where the\n // format is one of the strings in the preceding table.\n return {\n format: 'module',\n };\n }\n // Defer to Node.js for all other URLs.\n return defaultGetFormat(url, context, defaultGetFormat);\n}\n
"
},
{
"textRaw": "`getSource(url, context, defaultGetSource)`",
"type": "method",
"name": "getSource",
"signatures": [
{
"params": []
}
],
"desc": "\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
url
<string>context
<Object>\nformat
<string>defaultGetSource
<Function>source
<string> | <SharedArrayBuffer> | <Uint8Array>The getSource
hook provides a way to define a custom method for retrieving\nthe source code of an ES module specifier. This would allow a loader to\npotentially avoid reading files from disk.
/**\n * @param {string} url\n * @param {{ format: string }} context\n * @param {Function} defaultGetSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function getSource(url, context, defaultGetSource) {\n const { format } = context;\n if (Math.random() > 0.5) { // Some condition.\n // For some or all URLs, do some custom logic for retrieving the source.\n // Always return an object of the form {source: <string|buffer>}.\n return {\n source: '...',\n };\n }\n // Defer to Node.js for all other URLs.\n return defaultGetSource(url, context, defaultGetSource);\n}\n
"
},
{
"textRaw": "`transformSource(source, context, defaultTransformSource)`",
"type": "method",
"name": "transformSource",
"signatures": [
{
"params": []
}
],
"desc": "NODE_OPTIONS='--experimental-loader ./custom-loader.mjs' node x.js\n
\n\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
source
<string> | <SharedArrayBuffer> | <Uint8Array>context
<Object>\n\nsource
<string> | <SharedArrayBuffer> | <Uint8Array>The transformSource
hook provides a way to modify the source code of a loaded\nES module file after the source string has been loaded but before Node.js has\ndone anything with it.
If this hook is used to convert unknown-to-Node.js file types into executable\nJavaScript, a resolve hook is also necessary in order to register any\nunknown-to-Node.js file extensions. See the transpiler loader example below.
\n/**\n * @param {!(string | SharedArrayBuffer | Uint8Array)} source\n * @param {{\n * format: string,\n * url: string,\n * }} context\n * @param {Function} defaultTransformSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function transformSource(source, context, defaultTransformSource) {\n const { url, format } = context;\n if (Math.random() > 0.5) { // Some condition.\n // For some or all URLs, do some custom logic for modifying the source.\n // Always return an object of the form {source: <string|buffer>}.\n return {\n source: '...',\n };\n }\n // Defer to Node.js for all other sources.\n return defaultTransformSource(source, context, defaultTransformSource);\n}\n
"
},
{
"textRaw": "`getGlobalPreloadCode()`",
"type": "method",
"name": "getGlobalPreloadCode",
"signatures": [
{
"params": []
}
],
"desc": "\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
Sometimes it might be necessary to run some code inside of the same global scope\nthat the application runs in. This hook allows the return of a string that is\nrun as sloppy-mode script on startup.
\nSimilar 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)
.
If the code needs more advanced require
features, it has to construct\nits own require
using module.createRequire()
.
/**\n * @returns {string} Code to run before application startup\n */\nexport function getGlobalPreloadCode() {\n return `\\\nglobalThis.someInjectedProperty = 42;\nconsole.log('I just set some globals!');\n\nconst { createRequire } = getBuiltin('module');\n\nconst require = createRequire(process.cwd() + '/<preload>');\n// [...]\n`;\n}\n
"
}
],
"modules": [
{
"textRaw": "dynamicInstantiate
hook",
"name": "dynamicinstantiate
_hook",
"desc": "\n\nNote: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.
\n
To create a custom dynamic module that doesn't correspond to one of the\nexisting format
interpretations, the dynamicInstantiate
hook can be used.\nThis hook is called only for modules that return format: 'dynamic'
from\nthe getFormat
hook.
/**\n * @param {string} url\n * @returns {object} response\n * @returns {array} response.exports\n * @returns {function} response.execute\n */\nexport async function dynamicInstantiate(url) {\n return {\n exports: ['customExportName'],\n execute: (exports) => {\n // Get and set functions provided for pre-allocated export names\n exports.customExportName.set('value');\n }\n };\n}\n
\nWith the list of module exports provided upfront, the execute
function will\nthen be called at the exact point of module evaluation order for that module\nin the import tree.
The various loader hooks can be used together to accomplish wide-ranging\ncustomizations of Node.js’ code loading and evaluation behaviors.
", "type": "module", "displayName": "dynamicInstantiate
hook"
},
{
"textRaw": "HTTPS loader",
"name": "https_loader",
"desc": "In current Node.js, specifiers starting with https://
are unsupported. The\nloader below registers hooks to enable rudimentary support for such specifiers.\nWhile 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 'https';\n\nexport function resolve(specifier, context, defaultResolve) {\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 url: specifier\n };\n } else if (parentURL && parentURL.startsWith('https://')) {\n return {\n url: new URL(specifier, parentURL).href\n };\n }\n\n // Let Node.js handle all other specifiers.\n return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n // This loader assumes all network-provided JavaScript is ES module code.\n if (url.startsWith('https://')) {\n return {\n format: 'module'\n };\n }\n\n // Let Node.js handle all other URLs.\n return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function getSource(url, context, defaultGetSource) {\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({ source: data }));\n }).on('error', (err) => reject(err));\n });\n }\n\n // Let Node.js handle all other URLs.\n return defaultGetSource(url, context, defaultGetSource);\n}\n
\n// main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n
\nWith 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
.
Sources that are in formats Node.js doesn’t understand can be converted into\nJavaScript using the transformSource
hook. Before that hook gets called,\nhowever, other hooks need to tell Node.js not to throw an error on unknown file\ntypes; and to tell Node.js how to load this new file type.
This is less performant than transpiling source files before running\nNode.js; a transpiler loader should only be used for development and testing\npurposes.
\n// coffeescript-loader.mjs\nimport { URL, pathToFileURL } from 'url';\nimport CoffeeScript from 'coffeescript';\n\nconst baseURL = pathToFileURL(`${process.cwd()}/`).href;\n\n// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.\nconst extensionsRegex = /\\.coffee$|\\.litcoffee$|\\.coffee\\.md$/;\n\nexport function resolve(specifier, context, defaultResolve) {\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 if (extensionsRegex.test(specifier)) {\n return {\n url: new URL(specifier, parentURL).href\n };\n }\n\n // Let Node.js handle all other specifiers.\n return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\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. For the\n // purposes of this loader, all CoffeeScript URLs are ES modules.\n if (extensionsRegex.test(url)) {\n return {\n format: 'module'\n };\n }\n\n // Let Node.js handle all other URLs.\n return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function transformSource(source, context, defaultTransformSource) {\n const { url, format } = context;\n\n if (extensionsRegex.test(url)) {\n return {\n source: CoffeeScript.compile(source, { bare: true })\n };\n }\n\n // Let Node.js handle all other sources.\n return defaultTransformSource(source, context, defaultTransformSource);\n}\n
\n# main.coffee\nimport { scream } from './scream.coffee'\nconsole.log scream 'hello, world'\n\nimport { version } from 'process'\nconsole.log \"Brought to you by Node.js version #{version}\"\n
\n# scream.coffee\nexport scream = (str) -> str.toUpperCase()\n
\nWith 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.
The resolver has the following properties:
\nThe 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.
\nThe 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.
\nIn the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.
\ndefaultConditions is the conditional environment name array,\n[\"node\", \"import\"]
.
The resolver can throw the following errors:
\nESM_RESOLVE(specifier, parentURL)
\n\n\n\n
\n- Let resolved be undefined.
\n- If specifier is a valid URL, then\n
\n\n
\n- Set resolved to the result of parsing and reserializing\nspecifier as a URL.
\n- Otherwise, if specifier starts with \"/\", \"./\" or \"../\", then\n
\n\n
\n- Set resolved to the URL resolution of specifier relative to\nparentURL.
\n- Otherwise, if specifier starts with \"#\", then\n
\n\n
\n- Set resolved to the destructured value of the result of\nPACKAGE_IMPORTS_RESOLVE(specifier, parentURL,\ndefaultConditions).
\n- Otherwise,\n
\n\n
\n- Note: specifier is now a bare specifier.
\n- Set resolved the result of\nPACKAGE_RESOLVE(specifier, parentURL).
\n- If resolved contains any percent encodings of \"/\" or \"\\\" (\"%2f\"\nand \"%5C\" respectively), then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- If the file at resolved is a directory, then\n
\n\n
\n- Throw an Unsupported Directory Import error.
\n- If the file at resolved does not exist, then\n
\n\n
\n- Throw a Module Not Found error.
\n- Set resolved to the real path of resolved.
\n- Let format be the result of ESM_FORMAT(resolved).
\n- Load resolved as module format, format.
\n- Return resolved.
\n
PACKAGE_RESOLVE(packageSpecifier, parentURL)
\n\n\n\n
\n- Let packageName be undefined.
\n- If packageSpecifier is an empty string, then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- If packageSpecifier does not start with \"@\", then\n
\n\n
\n- Set packageName to the substring of packageSpecifier until the first\n\"/\" separator or the end of the string.
\n- Otherwise,\n
\n\n
\n- If packageSpecifier does not contain a \"/\" separator, then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Set packageName to the substring of packageSpecifier\nuntil the second \"/\" separator or the end of the string.
\n- If packageName starts with \".\" or contains \"\\\" or \"%\", then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Let packageSubpath be \".\" concatenated with the substring of\npackageSpecifier from the position at the length of packageName.
\n- Let selfUrl be the result of\nPACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
\n- If selfUrl is not undefined, return selfUrl.
\n- If packageSubpath is \".\" and packageName is a Node.js builtin\nmodule, then\n
\n\n
\n- Return the string \"node:\" concatenated with packageSpecifier.
\n- While parentURL is not the file system root,\n
\n\n
\n- Let packageURL be the URL resolution of \"node_modules/\"\nconcatenated with packageSpecifier, relative to parentURL.
\n- Set parentURL to the parent folder URL of parentURL.
\n- If the folder at packageURL does not exist, then\n
\n\n
\n- Set parentURL to the parent URL path of parentURL.
\n- Continue the next loop iteration.
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- If pjson is not null and pjson.exports is not null or\nundefined, then\n
\n\n
\n- Let exports be pjson.exports.
\n- Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath,\npjson.exports, defaultConditions).
\n- Otherwise, if packageSubpath is equal to \".\", then\n
\n\n
\n- Return the result applying the legacy LOAD_AS_DIRECTORY\nCommonJS resolver to packageURL, throwing a Module Not Found\nerror for no resolution.
\n- Otherwise,\n
\n\n
\n- Return the URL resolution of packageSubpath in packageURL.
\n- Throw a Module Not Found error.
\n
PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)
\n\n\n\n
\n- Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
\n- If packageURL is null, then\n
\n\n
\n- Return undefined.
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- If pjson is null or if pjson.exports is null or\nundefined, then\n
\n\n
\n- Return undefined.
\n- If pjson.name is equal to packageName, then\n
\n\n
\n- Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, subpath, pjson.exports,\ndefaultConditions).
\n- Otherwise, return undefined.
\n
PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)
\n\n\n\n
\n- If exports is an Object with both a key starting with \".\" and a key not\nstarting with \".\", throw an Invalid Package Configuration error.
\n- If subpath is equal to \".\", then\n
\n\n
\n- Let mainExport be undefined.
\n- If exports is a String or Array, or an Object containing no keys\nstarting with \".\", then\n
\n\n
\n- Set mainExport to exports.
\n- Otherwise if exports is an Object containing a \".\" property, then\n
\n\n
\n- Set mainExport to exports[\".\"].
\n- If mainExport is not undefined, then\n
\n\n
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, \"\", false, false,\nconditions).
\n- If resolved is not null or undefined, then\n
\n\n
\n- Return resolved.
\n- Otherwise, if exports is an Object and all keys of exports start with\n\".\", then\n
\n\n
\n- Let matchKey be the string \"./\" concatenated with subpath.
\n- Let resolvedMatch be result of PACKAGE_IMPORTS_EXPORTS_RESOLVE(\nmatchKey, exports, packageURL, false, conditions).
\n- If resolvedMatch.resolve is not null or undefined, then\n
\n\n
\n- Return resolvedMatch.
\n- Throw a Package Path Not Exported error.
\n
PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)
\n\n\n\n
\n- Assert: specifier begins with \"#\".
\n- If specifier is exactly equal to \"#\" or starts with \"#/\", then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
\n- If packageURL is not null, then\n
\n\n
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- If pjson.imports is a non-null Object, then\n
\n\n
\n- Let resolvedMatch be the result of\nPACKAGE_IMPORTS_EXPORTS_RESOLVE(specifier, pjson.imports,\npackageURL, true, conditions).
\n- If resolvedMatch.resolve is not null or undefined, then\n
\n\n
\n- Return resolvedMatch.
\n- Throw a Package Import Not Defined error.
\n
PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL,\nisImports, conditions)
\n\n\n\n
\n- If matchKey is a key of matchObj, and does not end in \"*\", then\n
\n\n
\n- Let target be the value of matchObj[matchKey].
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, \"\", false, isImports, conditions).
\n- Return the object { resolved, exact: true }.
\n- Let expansionKeys be the list of keys of matchObj ending in \"/\"\nor \"*\", sorted by length descending.
\n- For each key expansionKey in expansionKeys, do\n
\n\n
\n- If expansionKey ends in \"*\" and matchKey starts with but is\nnot equal to the substring of expansionKey excluding the last \"*\"\ncharacter, then\n
\n\n
\n- Let target be the value of matchObj[expansionKey].
\n- Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey minus one.
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, true, isImports,\nconditions).
\n- Return the object { resolved, exact: true }.
\n- If matchKey starts with expansionKey, then\n
\n\n
\n- Let target be the value of matchObj[expansionKey].
\n- Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey.
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, false, isImports,\nconditions).
\n- Return the object { resolved, exact: false }.
\n- Return the object { resolved: null, exact: true }.
\n
PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, pattern,\ninternal, conditions)
\n\n\n\n
\n- If target is a String, then\n
\n\n
\n- If pattern is false, subpath has non-zero length and target\ndoes not end with \"/\", throw an Invalid Module Specifier error.
\n- If target does not start with \"./\", then\n
\n\n
\n- If internal is true and target does not start with \"../\" or\n\"/\" and is not a valid URL, then\n
\n\n
\n- If pattern is true, then\n
\n\n
\n- Return PACKAGE_RESOLVE(target with every instance of\n\"*\" replaced by subpath, packageURL + \"/\")_.
\n- Return PACKAGE_RESOLVE(target + subpath,\npackageURL + \"/\")_.
\n- Otherwise, throw an Invalid Package Target error.
\n- If target split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments after the first segment, throw an\nInvalid Package Target error.
\n- Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
\n- Assert: resolvedTarget is contained in packageURL.
\n- If subpath split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments, throw an Invalid Module Specifier error.
\n- If pattern is true, then\n
\n\n
\n- Return the URL resolution of resolvedTarget with every instance of\n\"*\" replaced with subpath.
\n- Otherwise,\n
\n\n
\n- Return the URL resolution of the concatenation of subpath and\nresolvedTarget.
\n- Otherwise, if target is a non-null Object, then\n
\n\n
\n- If exports contains any index property keys, as defined in ECMA-262\n6.1.7 Array Index, throw an Invalid Package Configuration error.
\n- For each property p of target, in object insertion order as,\n
\n\n
\n- If p equals \"default\" or conditions contains an entry for p,\nthen\n
\n\n
\n- Let targetValue be the value of the p property in target.
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions).
\n- If resolved is equal to undefined, continue the loop.
\n- Return resolved.
\n- Return undefined.
\n- Otherwise, if target is an Array, then\n
\n\n
\n- If _target.length is zero, return null.
\n- For each item targetValue in target, do\n
\n\n
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions), continuing the loop on any Invalid Package Target\nerror.
\n- If resolved is undefined, continue the loop.
\n- Return resolved.
\n- Return or throw the last fallback resolution null return or error.
\n- Otherwise, if target is null, return null.
\n- Otherwise throw an Invalid Package Target error.
\n
ESM_FORMAT(url)
\n\n\n\n
\n- Assert: url corresponds to an existing file.
\n- Let pjson be the result of READ_PACKAGE_SCOPE(url).
\n- If url ends in \".mjs\", then\n
\n\n
\n- Return \"module\".
\n- If url ends in \".cjs\", then\n
\n\n
\n- Return \"commonjs\".
\n- If pjson?.type exists and is \"module\", then\n
\n\n
\n- If url ends in \".js\", then\n
\n\n
\n- Return \"module\".
\n- Throw an Unsupported File Extension error.
\n- Otherwise,\n
\n\n
\n- Throw an Unsupported File Extension error.
\n
READ_PACKAGE_SCOPE(url)
\n\n\n\n
\n- Let scopeURL be url.
\n- While scopeURL is not the file system root,\n
\n\n
\n- Set scopeURL to the parent URL of scopeURL.
\n- If scopeURL ends in a \"node_modules\" path segment, return null.
\n- Let pjson be the result of READ_PACKAGE_JSON(scopeURL).
\n- If pjson is not null, then\n
\n\n
\n- Return pjson.
\n- Return null.
\n
READ_PACKAGE_JSON(packageURL)
\n\n", "type": "module", "displayName": "Resolver Algorithm Specification" }, { "textRaw": "Customizing ESM specifier resolution algorithm", "name": "customizing_esm_specifier_resolution_algorithm", "desc": "\n
\n- Let pjsonURL be the resolution of \"package.json\" within packageURL.
\n- If the file at pjsonURL does not exist, then\n
\n\n
\n- Return null.
\n- If the file at packageURL does not parse as valid JSON, then\n
\n\n
\n- Throw an Invalid Package Configuration error.
\n- Return the parsed JSON source of the file at pjsonURL.
\n
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.
\nThe --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.
$ node index.mjs\nsuccess!\n$ node index # Failure!\nError: Cannot find module\n$ node --experimental-specifier-resolution=node index\nsuccess!\n
\n",
"type": "module",
"displayName": "Customizing ESM specifier resolution algorithm"
}
],
"type": "misc",
"displayName": "Resolution algorithm"
}
],
"properties": [
{
"textRaw": "`meta` {Object}",
"type": "Object",
"name": "meta",
"desc": "The import.meta
metaproperty is an Object
that contains the following\nproperty:
url
<string> The absolute file:
URL of the module.