[英]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.