Loaders#¶
History
Version
Changes
v18.6.0, v16.17.0
Add support for chaining loaders.
v16.12.0
Removed getFormat, getSource, transformSource, and globalPreload; added load hook and getGlobalPreload hook.
v8.8.0
Added in: v8.8.0
Stability: 1 - Experimental
This API is currently being redesigned and will still change.
To customize the default module resolution, loader hooks can optionally be provided via a --experimental-loader ./loader-name.mjs argument to Node.js.
When hooks are used they apply to each subsequent loader, the entry point, and all import calls. They won't apply to require calls; those still follow CommonJS rules.
Loaders follow the pattern of --require:
1 2 3 4 | |
These are called in the following sequence: cache-buster calls http-to-https which calls unpkg.
Hooks#¶
Hooks are part of a chain, even if that chain consists of only one custom (user-provided) hook and the default hook, which is always present. Hook functions nest: each one must always return a plain object, and chaining happens as a result of each function calling next<hookName>(), which is a reference to the subsequent loader's hook.
A hook that returns a value lacking a required property triggers an exception. A hook that returns without calling next<hookName>() and without returning shortCircuit: true also triggers an exception. These errors are to help prevent unintentional breaks in the chain.
resolve(specifier, context, nextResolve)#¶
History
Version
Changes
v18.6.0, v16.17.0
Add support for chaining resolve hooks. Each hook must either call nextResolve() or include a shortCircuit property set to true in its return.
v17.1.0, v16.14.0
Add support for import assertions.
The loaders API is being redesigned. This hook may disappear or its signature may change. Do not rely on the API described below.
specifiercontextconditionsExport conditions of the relevant package.jsonimportAssertionsparentURL| The module importing this one, or undefined if this is the Node.js entry point nextResolveThe subsequent resolvehook in the chain, or the Node.js defaultresolvehook after the last user-suppliedresolvehookspecifiercontext- Returns:
format| | A hint to the load hook (it might be ignored) 'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'shortCircuit| A signal that this hook intends to terminate the chain of resolvehooks. Default:falseurlThe absolute URL to which this input resolves
The resolve hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as 'module') as a hint to the load hook. If a format is specified, the load hook is ultimately responsible for providing the final format value (and it is free to ignore the hint provided by resolve); if resolve provides a format, a custom load hook is required even if only to pass the value to the Node.js default load hook.
The module specifier is the string in an import statement or import() expression.
The parent URL is the URL of the module that imported this one, or undefined if this is the main entry point for the application.
The conditions property in context is an array of conditions for package exports conditions that apply to this resolution request. They can be used for looking up conditional mappings elsewhere or to modify the list when calling the default resolution logic.
The current package exports conditions are always in the context.conditions array passed into the hook. To guarantee default Node.js module specifier resolution behavior when calling defaultResolve, the context.conditions array passed to it must include all elements of the context.conditions array originally passed into the resolve hook.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
load(url, context, nextLoad)#¶
History
Version
Changes
v18.6.0, v16.17.0
Add support for chaining load hooks. Each hook must either call nextLoad() or include a shortCircuit property set to true in its return.
The loaders API is being redesigned. This hook may disappear or its signature may change. Do not rely on the API described below.
In a previous version of this API, this was split across 3 separate, now deprecated, hooks (
getFormat,getSource, andtransformSource).
urlThe URL returned by the resolvechaincontextconditionsExport conditions of the relevant package.jsonformat| | The format optionally supplied by the resolvehook chainimportAssertionsnextLoadThe subsequent loadhook in the chain, or the Node.js defaultloadhook after the last user-suppliedloadhookspecifiercontext- Returns:
formatshortCircuit| A signal that this hook intends to terminate the chain of resolvehooks. Default:falsesource| | The source for Node.js to evaluate
The load hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. It is also in charge of validating the import assertion.
The final value of format must be one of the following:
format
Description
Acceptable types for source returned by load
'builtin'
Load a Node.js builtin module
Not applicable
'commonjs'
Load a Node.js CommonJS module
Not applicable
'json'
Load a JSON file
{ string, ArrayBuffer, TypedArray }
'module'
Load an ES module
{ string, ArrayBuffer, TypedArray }
'wasm'
Load a WebAssembly module
{ ArrayBuffer, TypedArray }
The value of source is ignored for type 'builtin' because currently it is not possible to replace the value of a Node.js builtin (core) module. The value of source is ignored for type 'commonjs' because the CommonJS module loader does not provide a mechanism for the ES module loader to override the CommonJS module return value. This limitation might be overcome in the future.
Caveat: The ESM
loadhook and namespaced exports from CommonJS modules are incompatible. Attempting to use them together will result in an empty object from the import. This may be addressed in the future.These types all correspond to classes defined in ECMAScript.
- The specific
ArrayBufferobject is aSharedArrayBuffer. - The specific
TypedArrayobject is aUint8Array.
If the source value of a text-based format (i.e., 'json', 'module') is not a string, it is converted to a string using util.TextDecoder.
The load hook provides a way to define a custom method for retrieving the source code of an ES module specifier. This would allow a loader to potentially avoid reading files from disk. It could also be used to map an unrecognized format to a supported one, for example yaml to module.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
In a more advanced scenario, this can also be used to transform an unsupported source to a supported one (see Examples below).
globalPreload()#¶
History
Version
Changes
v18.6.0, v16.17.0
Add support for chaining globalPreload hooks.
The loaders API is being redesigned. This hook may disappear or its signature may change. Do not rely on the API described below.
In a previous version of this API, this hook was named
getGlobalPreloadCode.
Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. This hook allows the return of a string that is run as a sloppy-mode script on startup.
Similar to how CommonJS wrappers work, the code runs in an implicit function scope. The only argument is a require-like function that can be used to load builtins like "fs": getBuiltin(request: string).
If the code needs more advanced require features, it has to construct its own require using module.createRequire().
1 2 3 4 5 6 7 8 9 10 11 12 | |
In order to allow communication between the application and the loader, another argument is provided to the preload code: port. This is available as a parameter to the loader hook and inside of the source text returned by the hook. Some care must be taken in order to properly call port.ref() and port.unref() to prevent a process from being in a state where it won't close normally.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
Examples#¶
The various loader hooks can be used together to accomplish wide-ranging customizations of the Node.js code loading and evaluation behaviors.
HTTPS loader#¶
In current Node.js, specifiers starting with https:// are experimental (see HTTPS and HTTP imports).
The loader below registers hooks to enable rudimentary support for such specifiers. While this may seem like a significant improvement to Node.js core functionality, there are substantial downsides to actually using this loader: performance is much slower than loading files from disk, there is no caching, and there is no security.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
With the preceding loader, running node --experimental-loader ./https-loader.mjs ./main.mjs prints the current version of CoffeeScript per the module at the URL in main.mjs.
Transpiler loader#¶
Sources that are in formats Node.js doesn't understand can be converted into JavaScript using the load hook. Before that hook gets called, however, a resolve hook needs to tell Node.js not to throw an error on unknown file types.
This is less performant than transpiling source files before running Node.js; a transpiler loader should only be used for development and testing purposes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | |
With the preceding loader, running node --experimental-loader ./coffeescript-loader.mjs main.coffee causes main.coffee to be turned into JavaScript after its source code is loaded from disk but before Node.js executes it; and so on for any .coffee, .litcoffee or .coffee.md files referenced via import statements of any loaded file.