A webpack loader which executes a given module, and returns the result of the
execution at build-time, when the module is required in the bundle. In this way,
the loader changes a module from code to a result.
Another way to view val-loader, is that it allows a user a way to make their
own custom loader logic, without having to write a custom loader.
The target module is called with two arguments: (options, loaderContext)
options: The loader options (for instance provided in the webpack config. See the example below).
Targeted modules of this loader must export a Function that returns an object,
or a Promise resolving an object (e.g. async function), containing a code property at a minimum, but can
contain any number of additional properties.
code
Type:
type code = string | Buffer;
Default: undefinedRequired
Code passed along to webpack or the next loader that will replace the module.
sourceMap
Type:
type sourceMap = object;
Default: undefined
A source map passed along to webpack or the next loader.
ast
Type:
type ast = Array<object>;
Default: undefined
An Abstract Syntax Tree
that will be passed to the next loader. Useful to speed up the build time if the
next loader uses the same AST.
dependencies
Type:
type dependencies = Array<string>;
Default: []
An array of absolute, native paths to file dependencies that should be watched by webpack for changes.
An array of absolute, native paths to directory dependencies that should be watched by webpack for changes.
Build dependencies can also be added using loaderContext.addBuildDependency(file: string).
cacheable
Type:
type cacheable = boolean;
Default: false
If true, specifies that the code can be re-used in watch mode if none of the
dependencies have changed.
Examples
Simple
In this example the loader is configured to operator on a file name of
years-in-ms.js, execute the code, and store the result in the bundle as the
result of the execution. This example passes years as an option, which
corresponds to the years parameter in the target module exported function:
years-in-ms.js
module.exports = function yearsInMs({ years }) { const value = years * 365 * 24 * 60 * 60 * 1000; // NOTE: this return value will replace the module in the bundle return { cacheable: true, code: "module.exports = " + value, };};