来自异步函数的 Webpack DefinePlugin

Bil*_*ton 6 javascript asynchronous node.js webpack

我想定义一些从异步资源返回的常量。无论如何要在 Webpack 中做到这一点?

/* webpack.config.js */
module.exports = {
    ...,
    plugins: [
        new webpack.DefinePlugin({
            someVar: /* RETURN VARIABLE FROM ASYNC FUNCTION */
        })
    ]
}
Run Code Online (Sandbox Code Playgroud)

Juh*_*nen 6

一个好方法是从 webpack 配置返回一个 Promise

webpack.config.js

...

module.exports = () => {
  return getYourAsyncResource().then((someVar) => {
    // Resolve as webpack configuration
    return {
      ...
      plugins: [
        new webpack.DefinePlugin({ someVar })
      ]
    };
  }) 
};
Run Code Online (Sandbox Code Playgroud)