val-loader
val-loader
执行给定的模块以在构建时生成源代码。
安装
npm install val-loader --save-dev
例子
如果你有一个findAnswer.js
这样的模块:
function findAnswer() {
return {
code: 'module.exports = 42;'
};
}
module.exports = findAnswer;
您可以使用 val-loader
在构建时生成源代码:
// webpack.config.js
module.exports = {
...
module: {
rules: [{
test: require.resolve('path/to/findAnswer.js'),
use: [{
loader: 'val-loader'
}]
}]
}
};
所有可用功能的完整示例如下所示:
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?'
}
}]
}]
}
};
Usage
使用该加载器加载的模块必须坚持以下接口:
加载的模块必须default
使用以下函数接口导出一个导出函数。
module.exports = function (...) { ... };
Babel 传输的模块也被支持。
export default function (...) { ... }
预期的功能界面
该函数将被加载器调用,options
并且必须返回:
- 具有以下对象接口的对象
- 承诺解析为以下对象接口
预期的对象接口
属性 | 类型 | 描述 |
---|---|---|
code | 串|缓冲器 | 需要。传递给下一个加载器或webpack的代码。 |
sourceMap | SourceMap | 可选的。将传递给下一个加载器或webpack。 |
ast | any | 可选的。一个将被传递给下一个加载器的抽象语法树。如果下一个加载器使用相同的AST,则可以加快构建时间。 |
dependencies | Array<string> | 默认值:[]。需要监视更改的文件依赖关系的绝对本地路径数组。 |
cacheable | boolean | 默认值:false。如果没有任何依赖关系发生变化,则标记代码是否可以在监视模式下重新使用。 |
加载程序选项
该 VAL-装载机
本身没有选项。这些选项按原样传递(不克隆它们)到导出的函数中。