1. val-loader
在构建时执行给定的模块以生成源代码。
1.1. 安装
npm install val-loader --save-dev
1.2. 用法
此loader加载的模块必须遵循以下接口
1.2.1. Module Interface
被加载的模块必须使用以下函数接口导出一个函数作为默认导出:
module.exports = function () {...};
被Babel 转换的模块也被支持
export default function (...) { ... }
1.2.2. Function Interface
该函数将使用loader选项来调用,并且必须返回一个对象或者Promise。
Object
Name | Type | Default | Description | |
---|---|---|---|---|
code |
`{String\ | Buffer}` | undefined |
(Required) The code that is passed to the next loader or to webpack |
sourceMap |
{Object} |
undefined |
(Optional) Will be passed to the next loader or to webpack | |
ast |
{Array<{Object}>} |
undefined |
(Optional) 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 |
{Array<{String}>} |
[] |
An array of absolute, native paths to file dependencies that need to be watched for changes | |
contextDependencies |
{Array<{String}>} |
[] |
An array of absolute, native paths to directory 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 |
Promise
解析上面的对象接口后的对象
1.3. Options
val-loader
itself has no options. The options are passed as they are (without cloning them) to the exported function
1.4. Examples
If you have a module like this
answer.js
function answer () {
return {
code: 'module.exports = 42;'
}
};
module.exports = answer;
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/answer.js'),
use: [
{
loader: 'val-loader'
}
]
}
]
}
};
1.4.1. Complete
A complete example of all available features looks like this
answer.js
const ask = require('./ask.js');
const generate = require('./generate.js');
function answer(options) {
return ask(options.question)
.then(generate)
.then(result => ({
ast: result.abstractSyntaxTree,
code: result.code,
// Mark dependencies of answer().
// 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('./generate.js')
],
// Flag the generated code as cacheable.
// If none of the dependencies have changed,
// the function won't be executed again.
cacheable: true
sourceMap: result.sourceMap,
})
);
}
module.exports = answer;
webpack.config.js
module.exports = {
...
module: {
rules: [
{
test: require.resolve('path/to/answer.js'),
use: [
{
loader: 'val-loader',
options: {
question: 'What is the meaning of life?'
}
}
]
}
]
}
};
1.5. 维护者
Juho Vepsäläinen |
Joshua Wiens |
Kees Kluskens |
Johannes Ewald |