Webpack:如何在构建时转换变量

l2a*_*lba 8 javascript variables performance webpack vue.js

关于使用Vue (vue-loader) + WebpackChromatism

示例:(在开发/源代码上)

let textColor = chromatism.contrastRatio('#ffea00').cssrgb // => rgb(0,0,0)
Run Code Online (Sandbox Code Playgroud)

是否可以告诉的WebPack转换rgb(0,0,0)内部版本

因此,构建版本应该转换为:(用于性能)

let textColor = 'rgb(0,0,0)'
Run Code Online (Sandbox Code Playgroud)

riy*_*ali 5

正如先前的答案和评论已经提到的那样,没有现成的AOT编译器可以处理这种情况(我的意思是这是一个非常特殊的情况,没有通用工具可以处理),没有什么可以阻止您的从推出自己的加载器/插件来完成此任务!
您可以使用自定义Webpack加载程序Node的VM模块在构建时执行代码,获取其输出并将其替换为源文件中的函数调用。
此想法的示例实现如下所示:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

然后在您的production.webpack.js(或类似文件)中,从此问题中获取

// Webpack config
resolveLoader: {
  alias: {
    'chromatism-optimizer': path.join(__dirname, './scripts/chromatism-optimizer'),
  },
}
// In module.rules
{
  test: /\.js$/,
  use: ['chromatism-optimizer'],
}
Run Code Online (Sandbox Code Playgroud)

注意:这只是参考实现,并且在很大程度上是不完整的。这里使用的正则表达式是非常基本的,可能无法涵盖许多其他用例,因此请确保您更新了正则表达式。而且,整个东西都可以使用webpack插件来实现(只是我对如何创建一个插件没有足够的了解)。要快速入门,请参阅此Wiki,以了解如何创建自定义插件。

基本思想很简单。

  1. 首先创建一个沙盒环境,
    let sandbox = { chromatism:chromatism, ...}

  2. 然后创建一个执行上下文,
    let context = new vm.createContext(sandbox)

  3. 然后,对于每个有效的源,在上下文中执行source语句并获取结果。
    let result = (new (vm.Source)(source)).runInContext(context)

  4. 然后用结果替换原始源语句。