There are currently the following loader hooks:
-
resolve
: Takes a specifier (the string afterfrom
in animport
statement) and converts it into an URL to be loaded. -
load
: Takes the resolved URL and returns runnable code (JavaScript, Wasm, etc.) as well as the name of one of Node’s ESM loader’s “translators”:commonjs
module
builtin
(a Node internal module, likefs
)json
(with--experimental-json-modules
)wasm
(with--experimental-wasm-modules
)
The Node resolution algorithms may rely on various filesystem operations in order to return definite answers. For example, in order to know whether the package foo
resolves to /path/to/foo/index.js
, one must first check the exports
field located in /path/to/foo/package.json
. Similarly, a loader that would add support for import maps need to know how to retrieve those import maps in the first place.
While this is fairly easy when operating with the traditional filesystem (one could just use the fs
module), things get trickier when you consider that loaders may also have to deal with other data sources. For instance, a loader that would import files directly from the network (similar to how Deno operates) would be unable to leverage fs
to access the package.json
content for the remote packages. Same thing when the package data are kept within archives that would require special support for access (like Electron or Yarn both operate).
To facilitate such interactions between loaders, they are given the ability to override the basic filesystem operations used by the Node resolution helpers. This way, they can remain blissfully unaware of the underlying data source (filesystem or network or otherwise) and focus on the part of the resolution they care about.
-
statFile
: Takes the resolved URL and returns itsfs.Stats
record (ornull
if it doesn't exist). -
readFile
: Takes the resolved URL and returns its binary content (ornull
if it doesn't exist).
globalPreload
: Defines a string of JavaScript to be injected into the application global scope.
Custom loaders are intended to chain to support various concerns beyond the scope of core, such as build tooling, mocking, transpilation, etc.
The initial experimental implementation consisted of 5 hooks:
resolve
getFormat
getSource
transformSource
getGlobalPreloadCode
These were consolidated (in nodejs/node#37468) to avoid counter-intuitive and paradoxical behaviour when used in multiple custom loaders.