npm install val-loader --save-dev
If you have a module findAnswer.js
like this:
function findAnswer() { return { code: 'module.exports = 42;' }; } module.exports = findAnswer;
you can use the val-loader to generate source code on build time:
// webpack.config.js module.exports = { ... module: { rules: [{ test: require.resolve('path/to/findAnswer.js'), use: [{ loader: 'val-loader' }] }] } };
A complete example of all available features looks like this:
const ask = require('./ask.js'); const generateResult = require('./generateResult.js'); function findAnswer(options) { return ask(options.question) .then(generateResult) .then(result => ({ code: result.code, sourceMap: result.sourceMap, ast: result.abstractSyntaxTree, // Mark dependencies of findAnswer(). // The function will be re-executed if one of these // dependencies has changed in watch mode. dependencies: [ // Array of absolute native paths! require.resolve('./ask.js'), require.resolve('./generateResult.js') ], // Flag the generated code as cacheable. // If none of the dependencies have changed, // the function won't be executed again. cacheable: true })); } module.exports = findAnswer;
// webpack.config.js module.exports = { ... module: { rules: [{ test: require.resolve('path/to/findAnswer.js'), use: [{ loader: 'val-loader', options: { question: 'What is the meaning of life?' } }] }] } };
The module that is loaded with this loader must stick to the following interfaces:
The loaded module must export a function as default
export with the following function interface.
module.exports = function (...) { ... };
Modules transpiled by Babel are also supported.
export default function (...) { ... }
The function will be called with the loader options
and must either return:
code
sourceMap
ast
any
dependencies
Array<string>
[]
. An array of absolute, native paths to file dependencies that need to be watched for changes. cacheable
boolean
false
. Flag whether the code can be re-used in watch mode if none of the dependencies
have changed. The val-loader itself has no options. The options are passed as they are (without cloning them) to the exported function.
© 2012–2016 Tobias Koppers
Licensed under the Creative Commons Attribution License 4.0.
https://webpack.js.org/loaders/val-loader/