【问题标题】:Conditional Import of JavaScript module by Webpack通过 Webpack 条件导入 JavaScript 模块
【发布时间】:2018-03-16 07:56:27
【问题描述】:

我有一个基于 Webpack 的 JavaScript 框架。我想通过 Webpack 配置中的自定义条件导入(或不导入)任意模块(具有默认导出的自定义函数的 JavaScript 文件):

// in webpack.customSettings.js
module.exports = {
  const customJsFilePath = 'path/to/custom/js/file';
  // alternatively, if no import is desired:
  // const customJsFilePath = null;
};

// in webpack.config.js
const settings = require('./webpack.customSettings.js');
// ...
new webpack.DefinePlugin({
  'process.env': {
    PATH: JSON.stringify(settings.customJsFilePath || ''),
  },
});

这决定了在 Webpack 构建过程中是否需要以及需要​​哪个自定义模块。所以像下面这样的动态导入似乎是不必要的,而且效率不高,因为路径在运行时已经固定,在这种情况下我不想在运行时动态加载额外的文件(块):

// somewhere in my main index.js
if (process.env.PATH) {
  import(`${process.env.PATH}/index.js`).then((module) => {
    const myFunc = module.default;
    // ...
  });
}

我希望 Webpack 将自定义文件直接包含在我的捆绑包中。类似的东西:

// somewhere in my main index.js
const myFunc = awesomeGlobal.customFunc;
if (myFunc) {
  // ...
}

很遗憾,我知道以下方法不起作用:

// in my main index.js
import customFunc from `${process.env.PATH}/index.js`;

但是我能做什么呢?也许 Webpack 中有一些东西?

【问题讨论】:

    标签: javascript webpack


    【解决方案1】:

    好的,我自己想出了解决方案。我使用 Webpack ProvidePlugin 有条件地提供模块:

    // in webpack.customSettings.js
    module.exports = {
      const customJsFilePath = 'path/to/custom/js/file';
      // alternatively, if no import is desired:
      // const customJsFilePath = null;
    };
    
    // in webpack.config.js
    const settings = require('./webpack.customSettings.js');
    // ...
    new webpack.ProvidePlugin((() => {
      const addModules = {};
    
      if (settings.customJsFilePath) {
        addModules['window.myFunc'] = [settings.customJsFilePath, 'default'];
      }
    
      return addModules;
    })()),
    
    // in my main index.js
    if (window.myFunc) {
      window.myFunc();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-11
      • 2022-11-24
      • 1970-01-01
      • 2019-03-03
      • 2019-11-10
      • 2022-06-28
      • 1970-01-01
      • 2021-11-06
      • 2012-11-06
      相关资源
      最近更新 更多