Lines Matching +full:import +full:- +full:module
1 # Modules: `node:module` API
3 <!--introduced_in=v12.20.0-->
5 <!-- YAML
7 -->
9 ## The `Module` object
14 `Module`, the [`module`][] variable often seen in [CommonJS][] modules. Accessed
15 via `import 'node:module'` or `require('node:module')`.
17 ### `module.builtinModules`
19 <!-- YAML
21 - v9.3.0
22 - v8.10.0
23 - v6.13.0
24 -->
29 if a module is maintained by a third party or not.
31 `module` in this context isn't the same object that's provided
32 by the [module wrapper][]. To access it, require the `Module` module:
35 // module.mjs
36 // In an ECMAScript module
37 import { builtinModules as builtin } from 'node:module';
41 // module.cjs
42 // In a CommonJS module
43 const builtin = require('node:module').builtinModules;
46 ### `module.createRequire(filename)`
48 <!-- YAML
50 -->
58 import { createRequire } from 'node:module';
59 const require = createRequire(import.meta.url);
61 // sibling-module.js is a CommonJS module.
62 const siblingModule = require('./sibling-module');
65 ### `module.isBuiltin(moduleName)`
67 <!-- YAML
69 -->
71 * `moduleName` {string} name of the module
72 * Returns: {boolean} returns true if the module is builtin else returns false
75 import { isBuiltin } from 'node:module';
81 ### `module.register(specifier[, parentURL][, options])`
83 <!-- YAML
86 - version: v18.19.0
87 pr-url: https://github.com/nodejs/node/pull/49655
89 -->
91 > Stability: 1.1 - Active development
94 the same string that would be passed to `import()`, except that if it is
97 URL, such as `import.meta.url`, you can pass that URL here. **Default:**
105 Register a module that exports [hooks][] that customize Node.js module
108 ### `module.syncBuiltinESMExports()`
110 <!-- YAML
112 -->
114 The `module.syncBuiltinESMExports()` method updates all the live bindings for
121 const { syncBuiltinESMExports } = require('node:module');
135 import('node:fs').then((esmFS) => {
151 <!-- YAML
154 - version: v18.19.0
155 pr-url: https://github.com/nodejs/node/pull/48842
157 - version:
158 - v18.6.0
159 - v16.17.0
160 pr-url: https://github.com/nodejs/node/pull/42623
162 - version: v16.12.0
163 pr-url: https://github.com/nodejs/node/pull/37468
166 -->
168 > Stability: 1.1 - Active development
170 <!-- type=misc -->
176 Module resolution and loading can be customized by registering a file which
178 from `node:module`, which you can run before your application code by
179 using the `--import` flag:
182 node --import ./register-hooks.js ./my-app.js
186 // register-hooks.js
187 import { register } from 'node:module';
189 register('./hooks.mjs', import.meta.url);
193 // register-hooks.js
194 const { register } = require('node:module');
200 The file passed to `--import` can also be an export from a dependency:
203 node --import some-package/register ./my-app.js
206 Where `some-package` has an [`"exports"`][] field defining the `/register`
207 export to map to a file that calls `register()`, like the following `register-hooks.js`
210 Using `--import` ensures that the hooks are registered before any application
212 `register` can be called from the entry point, but dynamic `import()` must be
216 import { register } from 'node:module';
218 register('http-to-https', import.meta.url);
220 // Because this is a dynamic `import()`, the `http-to-https` hooks will run
221 // to handle `./my-app.js` and any other files it imports or requires.
222 await import('./my-app.js');
226 const { register } = require('node:module');
229 register('http-to-https', pathToFileURL(__filename));
231 // Because this is a dynamic `import()`, the `http-to-https` hooks will run
232 // to handle `./my-app.js` and any other files it imports or requires.
233 import('./my-app.js');
236 In this example, we are registering the `http-to-https` hooks, but they will
237 only be available for subsequently imported modules—in this case, `my-app.js`
238 and anything it references via `import` (and optionally `require`). If the
239 `import('./my-app.js')` had instead been a static `import './my-app.js'`, the
240 app would have _already_ been loaded **before** the `http-to-https` hooks were
243 be static imports _within_ `my-app.js`, which will not be evaluated until
244 `my-app.js` is dynamically imported.
246 `my-app.js` can also be CommonJS. Customization hooks will run for any
247 modules that it references via `import` (and optionally `require`).
251 URL to `--import`:
254 …--import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } fr…
263 import { register } from 'node:module';
265 register('./first.mjs', import.meta.url);
266 register('./second.mjs', import.meta.url);
267 await import('./my-app.mjs');
272 const { register } = require('node:module');
278 import('./my-app.mjs');
287 `first.mjs`. This allows for things like writing hooks in non-JavaScript
291 The `register` method cannot be called from within the module that defines the
294 ### Communication with module customization hooks
296 Module customization hooks run on a dedicated thread, separate from the main
305 import { register } from 'node:module';
306 import { MessageChannel } from 'node:worker_threads';
316 register('./my-hooks.mjs', {
317 parentURL: import.meta.url,
324 const { register } = require('node:module');
336 register('./my-hooks.mjs', {
345 The [`register`][] method can be used to register a module that exports a set of
347 module resolution and loading process. The exported functions must have specific
356 // Take an `import` or `require` specifier and resolve it to a URL.
365 (user-provided) hook and the default hook, which is always present. Hook
383 <!-- YAML
385 -->
387 > Stability: 1.1 - Active development
389 * `data` {any} The data from `register(loader, import.meta.url, { data })`.
392 the hooks thread when the hooks module is initialized. Initialization happens
393 when the hooks module is registered via [`register`][].
400 Module customization code:
403 // path-to-my-hooks.js
413 import assert from 'node:assert';
414 import { register } from 'node:module';
415 import { MessageChannel } from 'node:worker_threads';
426 register('./path-to-my-hooks.js', {
427 parentURL: import.meta.url,
435 const { register } = require('node:module');
448 register('./path-to-my-hooks.js', {
457 <!-- YAML
459 - version: v18.19.0
460 pr-url: https://github.com/nodejs/node/pull/50140
464 - version:
465 - v18.6.0
466 - v16.17.0
467 pr-url: https://github.com/nodejs/node/pull/42623
471 - version:
472 - v17.1.0
473 - v16.14.0
474 pr-url: https://github.com/nodejs/node/pull/40250
475 description: Add support for import assertions.
476 -->
478 > Stability: 1.2 - Release candidate
483 * `importAttributes` {Object} An object whose key-value pairs represent the
484 attributes for the module to import
485 * `parentURL` {string|undefined} The module importing this one, or undefined
488 Node.js default `resolve` hook after the last user-supplied `resolve` hook
494 `'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'`
495 * `importAttributes` {Object|undefined} The import attributes to use when
496 caching the module (optional; if excluded the input will be used)
505 how to cache a given `import` statement or expression, or `require` call. It can
506 optionally return a format (such as `'module'`) as a hint to the `load` hook. If
512 Import type attributes are part of the cache key for saving loaded modules into
513 the internal module cache. The `resolve` hook is responsible for returning an
514 `importAttributes` object if the module should be cached with different
524 Node.js module specifier resolution behavior_ when calling `defaultResolve`, the
548 conditions: [...context.conditions, 'another-condition'],
553 // Node.js default resolve if this is the last user-specified loader.
560 <!-- YAML
562 - version:
563 - v18.6.0
564 - v16.17.0
565 pr-url: https://github.com/nodejs/node/pull/42623
569 -->
571 > Stability: 1.2 - Release candidate
580 Node.js default `load` hook after the last user-supplied `load` hook
591 validating the import assertion.
596 | ------------ | ------------------------------ | -------------------------------------------------…
597 | `'builtin'` | Load a Node.js builtin module | Not applicable …
598 | `'commonjs'` | Load a Node.js CommonJS module | Not applicable …
600 | `'module'` | Load an ES module | { [`string`][], [`ArrayBuffer`][], [`TypedArray`]…
601 | `'wasm'` | Load a WebAssembly module | { [`ArrayBuffer`][], [`TypedArray`][] } …
604 not possible to replace the value of a Node.js builtin (core) module. The value
605 of `source` is ignored for type `'commonjs'` because the CommonJS module loader
606 does not provide a mechanism for the ES module loader to override the
607 [CommonJS module return value](esm.md#commonjs-namespaces). This limitation
612 > object from the import. This may be addressed in the future.
619 If the source value of a text-based format (i.e., `'json'`, `'module'`)
625 a supported one, for example `yaml` to `module`.
656 <!-- YAML
658 - version:
659 - v18.6.0
660 - v16.17.0
661 pr-url: https://github.com/nodejs/node/pull/42623
663 -->
665 > Stability: 1.0 - Early development
668 > [`initialize`][] instead. When a hooks module has an `initialize` export,
677 that is run as a sloppy-mode script on startup.
680 scope. The only argument is a `require`-like function that can be used to load
684 its own `require` using `module.createRequire()`.
692 const { createRequire } = getBuiltin('module');
729 The various module customization hooks can be used together to accomplish
730 wide-ranging customizations of the Node.js code loading and evaluation
733 #### Import from HTTPS
745 // https-hooks.mjs
746 import { get } from 'node:https';
758 // This example assumes all network-provided JavaScript is ES module
760 format: 'module',
775 import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';
780 With the preceding hooks module, running
781 …ode --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL …
782 prints the current version of CoffeeScript per the module at the URL in
794 // coffeescript-hooks.mjs
795 import { readFile } from 'node:fs/promises';
796 import { dirname, extname, resolve as resolvePath } from 'node:path';
797 import { cwd } from 'node:process';
798 import { fileURLToPath, pathToFileURL } from 'node:url';
799 import coffeescript from 'coffeescript';
834 // work for most projects but does not cover some edge-cases (such as
860 import { scream } from './scream.coffee'
863 import { version } from 'node:process'
869 export scream = (str) -> str.toUpperCase()
872 With the preceding hooks module, running
873 …--import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } fr…
876 `.litcoffee` or `.coffee.md` files referenced via `import` statements of any
879 #### Import maps
882 `resolve` hook. This hooks module reads an `import-map.json` file that defines
884 implementation of a small subset of the "import maps" specification).
887 // import-map-hooks.js
888 import fs from 'node:fs/promises';
890 const { imports } = JSON.parse(await fs.readFile('import-map.json'));
905 import 'a-module';
909 // import-map.json
912 "a-module": "./some-module.js"
918 // some-module.js
919 console.log('some module!');
922 … --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } f…
923 should print `some module!`.
927 <!-- YAML
929 - v13.7.0
930 - v12.17.0
931 -->
933 > Stability: 1 - Experimental
940 [`--enable-source-maps`][], or with code coverage enabled by setting
944 // module.mjs
945 // In an ECMAScript module
946 import { findSourceMap, SourceMap } from 'node:module';
950 // module.cjs
951 // In a CommonJS module
952 const { findSourceMap, SourceMap } = require('node:module');
955 <!-- Anchors to make sure old links find a target -->
959 ### `module.findSourceMap(path)`
961 <!-- YAML
963 - v13.7.0
964 - v12.17.0
965 -->
968 * Returns: {module.SourceMap|undefined} Returns `module.SourceMap` if a source
974 ### Class: `module.SourceMap`
976 <!-- YAML
978 - v13.7.0
979 - v12.17.0
980 -->
1006 * `lineOffset` {number} The zero-indexed line number offset in
1008 * `columnOffset` {number} The zero-indexed column number offset
1031 SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and
1035 To get the corresponding 1-indexed line and column numbers from a
1042 * `lineNumber` {number} The 1-indexed line number of the call
1044 * `columnOffset` {number} The 1-indexed column number
1048 Given a 1-indexed lineNumber and columnNumber from a call site in
1060 * lineNumber: {number} The 1-indexed lineNumber of the
1062 * columnNumber: {number} The 1-indexed columnNumber of the
1066 [Conditional exports]: packages.md#conditional-exports
1067 [Customization hooks]: #customization-hooks
1069 [HTTPS and HTTP imports]: esm.md#https-and-http-imports
1072 [`--enable-source-maps`]: cli.md#--enable-source-maps
1073 [`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/A…
1075 [`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Obj…
1076 [`SourceMap`]: #class-modulesourcemap
1077 [`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Ty…
1078 [`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Ui…
1080 [`module`]: modules.md#the-module-object
1083 [`register`]: #moduleregisterspecifier-parenturl-options
1084 [`string`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
1085 [`util.TextDecoder`]: util.md#class-utiltextdecoder
1086 [hooks]: #customization-hooks
1087 [load hook]: #loadurl-context-nextload
1088 [module wrapper]: modules.md#the-module-wrapper
1091 [transferrable objects]: worker_threads.md#portpostmessagevalue-transferlist