{ "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.

\n

Not 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.

\n

Once this has been set, files ending with .mjs will be able to be loaded\nas ES Modules.

\n
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:

\n" } ], "type": "misc", "displayName": "Supported" }, { "textRaw": "Unsupported", "name": "unsupported", "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n
FeatureReason
require('./foo.mjs')ES Modules have differing resolution and timing, use dynamic import
", "type": "misc", "displayName": "Unsupported" } ] }, { "textRaw": "Notable differences between `import` and `require`", "name": "notable_differences_between_`import`_and_`require`", "modules": [ { "textRaw": "No NODE_PATH", "name": "no_node_path", "desc": "

NODE_PATH is not part of resolving import specifiers. Please use symlinks\nif this behavior is desired.

", "type": "module", "displayName": "No NODE_PATH" }, { "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.

", "type": "module", "displayName": "No `require.extensions`" }, { "textRaw": "No `require.cache`", "name": "no_`require.cache`", "desc": "

require.cache is not used by import. It has a separate cache.

", "type": "module", "displayName": "No `require.cache`" }, { "textRaw": "URL based paths", "name": "url_based_paths", "desc": "

ESM are resolved and cached based upon URL\nsemantics. This means that files containing special characters such as # and\n? need to be escaped.

\n

Modules will be loaded multiple times if the import specifier used to resolve\nthem have a different query or fragment.

\n
import './foo?query=1'; // loads ./foo with query of \"?query=1\"\nimport './foo?query=2'; // loads ./foo with query of \"?query=2\"\n
\n

For now, only modules using the file: protocol can be loaded.

", "type": "module", "displayName": "URL based paths" } ], "type": "misc", "displayName": "Notable differences between `import` and `require`" }, { "textRaw": "Interop with existing modules", "name": "interop_with_existing_modules", "desc": "

All CommonJS, JSON, and C++ modules can be used with import.

\n

Modules loaded this way will only be loaded once, even if their query\nor fragment string differs between import statements.

\n

When loaded via import these modules will provide a single default export\nrepresenting the value of module.exports at the time they finished evaluating.

\n
// foo.js\nmodule.exports = { one: 1 };\n\n// bar.mjs\nimport foo from './foo.js';\nfoo.one === 1; // true\n
\n

Builtin 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.

\n
import EventEmitter from 'events';\nconst e = new EventEmitter();\n
\n
import { readFile } from 'fs';\nreadFile('./foo.txt', (err, source) => {\n  if (err) {\n    console.error(err);\n  } else {\n    console.log(source);\n  }\n});\n
\n
import 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.

\n

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:

\n
const 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
\n

The parentModuleURL is provided as undefined when performing main Node.js\nload itself.

\n

The default Node.js ES module resolution function is provided as a third\nargument to the resolver for easy compatibility workflows.

\n

In 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:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
formatDescription
'esm'Load a standard JavaScript module
'cjs'Load a node-style CommonJS module
'builtin'Load a node builtin CommonJS module
'json'Load a JSON file
'addon'Load a C++ Addon
'dynamic'Use 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:

\n
import 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
\n

With this loader, running:

\n
NODE_OPTIONS='--experimental-modules --loader ./custom-loader.mjs' node x.js\n
\n

would load the module x.js as an ES module with relative resolution support\n(with node_modules loading skipped in this example).

", "type": "misc", "displayName": "Resolve hook" }, { "textRaw": "Dynamic instantiate hook", "name": "dynamic_instantiate_hook", "desc": "

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.

\n
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
\n

With 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.

", "type": "misc", "displayName": "Dynamic instantiate hook" } ] } ] } ] }