{ "type": "module", "source": "doc/api/esm.md", "introduced_in": "v8.5.0", "stability": 1, "stabilityText": "Experimental", "miscs": [ { "textRaw": "ECMAScript Modules", "name": "esm", "introduced_in": "v8.5.0", "type": "misc", "stability": 1, "stabilityText": "Experimental", "desc": "
Node.js contains support for ES Modules based upon the\nNode.js EP for ES Modules.
\nNot all features of the EP are complete and will be landing as both VM support\nand implementation is ready. Error messages are still being polished.
", "miscs": [ { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "The --experimental-modules
flag can be used to enable features for loading\nESM modules.
Once this has been set, files ending with .mjs
will be able to be loaded\nas ES Modules.
node --experimental-modules my-app.mjs\n
"
},
{
"textRaw": "Features",
"name": "Features",
"type": "misc",
"miscs": [
{
"textRaw": "Supported",
"name": "supported",
"desc": "Only the CLI argument for the main entry point to the program can be an entry\npoint into an ESM graph. Dynamic import can also be used to create entry points\ninto ESM graphs at runtime.
", "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.Feature | \nReason | \n
---|---|
require('./foo.mjs') | \nES Modules have differing resolution and timing, use dynamic import | \n
NODE_PATH
is not part of resolving import
specifiers. Please use symlinks\nif this behavior is desired.
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.
ESM are resolved and cached based upon URL\nsemantics. This means that files containing special characters such as #
and\n?
need to be escaped.
Modules will be loaded multiple times if the import
specifier used to resolve\nthem have a different query or fragment.
import './foo?query=1'; // loads ./foo with query of \"?query=1\"\nimport './foo?query=2'; // loads ./foo with query of \"?query=2\"\n
\nFor now, only modules using the file:
protocol can be loaded.
All CommonJS, JSON, and C++ modules can be used with import
.
Modules loaded this way will only be loaded once, even if their query\nor fragment string differs between import
statements.
When loaded via import
these modules will provide a single default
export\nrepresenting the value of module.exports
at the time they finished evaluating.
// foo.js\nmodule.exports = { one: 1 };\n\n// bar.js\nimport foo from './foo.js';\nfoo.one === 1; // true\n
\nBuiltin modules will provide named exports of their public API, as well as a\ndefault export which can be used for, among other things, modifying the named\nexports. Named exports of builtin modules are updated when the corresponding\nexports property is accessed, redefined, or deleted.
\nimport 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';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\n\nfs.readFileSync === readFileSync;\n
",
"type": "misc",
"displayName": "Interop with existing modules"
},
{
"textRaw": "Loader hooks",
"name": "Loader hooks",
"type": "misc",
"desc": "To customize the default module resolution, loader hooks can optionally be\nprovided via a --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": "Resolve hook", "name": "resolve_hook", "desc": "The resolve hook returns the resolved file URL and module format for a\ngiven module specifier and parent file URL:
\nconst baseURL = new URL('file://');\nbaseURL.pathname = `${process.cwd()}/`;\n\nexport async function resolve(specifier,\n parentModuleURL = baseURL,\n defaultResolver) {\n return {\n url: new URL(specifier, parentModuleURL).href,\n format: 'esm'\n };\n}\n
\nThe parentModuleURL
is provided as undefined
when performing main Node.js\nload itself.
The default Node.js ES module resolution function is provided as a third\nargument to the resolver for easy compatibility workflows.
\nIn addition to returning the resolved file URL value, the resolve hook also\nreturns a format
property specifying the module format of the resolved\nmodule. This can be one of the following:
format | \nDescription | \n
---|---|
'esm' | \nLoad a standard JavaScript module | \n
'cjs' | \nLoad a node-style CommonJS module | \n
'builtin' | \nLoad a node builtin CommonJS module | \n
'json' | \nLoad a JSON file | \n
'addon' | \nLoad a C++ Addon | \n
'dynamic' | \nUse a dynamic instantiate hook | \n
For example, a dummy loader to load JavaScript restricted to browser resolution\nrules with only JS file extension and Node.js builtin modules support could\nbe written:
\nimport path from 'path';\nimport process from 'process';\nimport Module from 'module';\n\nconst builtins = Module.builtinModules;\nconst JS_EXTENSIONS = new Set(['.js', '.mjs']);\n\nconst baseURL = new URL('file://');\nbaseURL.pathname = `${process.cwd()}/`;\n\nexport function resolve(specifier, parentModuleURL = baseURL, defaultResolve) {\n if (builtins.includes(specifier)) {\n return {\n url: specifier,\n format: 'builtin'\n };\n }\n if (/^\\.{0,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) {\n // For node_modules support:\n // return defaultResolve(specifier, parentModuleURL);\n throw new Error(\n `imports must begin with '/', './', or '../'; '${specifier}' does not`);\n }\n const resolved = new URL(specifier, parentModuleURL);\n const ext = path.extname(resolved.pathname);\n if (!JS_EXTENSIONS.has(ext)) {\n throw new Error(\n `Cannot load file with non-JavaScript file extension ${ext}.`);\n }\n return {\n url: resolved.href,\n format: 'esm'\n };\n}\n
\nWith this loader, running:
\nNODE_OPTIONS='--experimental-modules --loader ./custom-loader.mjs' node x.js\n
\nwould load the module x.js
as an ES module with relative resolution support\n(with node_modules
loading skipped in this example).
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 resolve
hook.
export 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.