网站搜索

javascript - 从异步函数使用 Webpack DefinePlugin


我想定义一些从异步资源返回的常量。有什么办法可以在 Webpack 中做到这一点吗?

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

答案#1

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

webpack.config.js

...

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