[英]Conditional Import of JavaScript module by Webpack
我有一个基于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中有东西?
好的,我自己想出了解决方案。 我使用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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.