正如之前的答案和 cmets 已经提到的,没有现成的 AOT 编译器来处理这种情况(我的意思是这是一个非常特殊的情况,没有通用工具能够处理它),有没有什么能阻止您推出自己的加载器/插件来处理此任务!
您可以使用自定义 Webpack Loader 和 Node's VM Module 在构建时执行代码,获取其输出并将其替换为源文件中的函数调用。
这个想法的一个示例实现看起来像下面的 sn-p:
// file: chromatismOptimizer.js
// node's vm module https://nodejs.org/api/vm.html
const vm = require('vm')
const chromatism = require('chromatism')
// a basic and largley incomplete regex to extract lines where chromatism is called
let regex = /^(.*)(chromatism\S*)(.*)$/
// create a Sandbox
//https://nodejs.org/api/vm.html#vm_what_does_it_mean_to_contextify_an_object
// this is roughly equivalent to the global the context the script will execute in
let sandbox = {
chromatism: chromatism
}
// now create an execution context for the script
let context = new vm.createContext(sandbox)
// export a webpack sync loader function
module.exports = function chromatismOptimizer(source){
let compiled = source.split('\n').reduce((agg, line) => {
let parsed = line.replace(regex, (ig, x, source, z) => {
// parse and execute the script inside the context
// return value is the result of execution
// https://nodejs.org/api/vm.html#vm_script_runincontext_contextifiedsandbox_options
let res = (new (vm.Script)(source)).runInContext(context)
return `${x}'${res}'${z? z : ''}`
})
agg.push(parsed)
return agg;
}, []).join('\n');
return compiled;
}
然后在您的 production.webpack.js(或类似的文件)中取自 this issue:
// Webpack config
resolveLoader: {
alias: {
'chromatism-optimizer': path.join(__dirname, './scripts/chromatism-optimizer'),
},
}
// In module.rules
{
test: /\.js$/,
use: ['chromatism-optimizer'],
}
注意:这只是一个参考实现,基本上是不完整的。此处使用的正则表达式非常基础,可能无法涵盖许多其他用例,因此请确保更新正则表达式。此外,这一切都可以使用 webpack 插件来实现(只是我没有足够的知识来创建一个)。对于快速入门refer to this wiki 了解如何创建自定义插件。
基本思想很简单。
首先创建一个沙盒环境,
let sandbox = { chromatism:chromatism, ...}
然后创建一个执行上下文,
let context = new vm.createContext(sandbox)
然后对于每个有效的源,在上下文中执行源语句并得到结果。
let result = (new (vm.Source)(source)).runInContext(context)
然后可能用结果替换原来的源语句。