I have a JavaScript Framework based on Webpack. There I want to import (or not) an arbitrary module (JavaScript file with a custom function exported as default) by a custom condition made in the Webpack configuration:
// 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 || ''),
},
});
This determines if and which custom module is required during the Webpack build process. So a dynamic import like the following seems to be unnecessary and not really efficient, because the path is already fixed at runtime and I don't want to load dynamically an extra file (chunk) during runtime in this case:
// somewhere in my main index.js
if (process.env.PATH) {
import(`${process.env.PATH}/index.js`).then((module) => {
const myFunc = module.default;
// ...
});
}
I would rather have the custom file included directly in my bundle by Webpack. Something like that:
// somewhere in my main index.js
const myFunc = awesomeGlobal.customFunc;
if (myFunc) {
// ...
}
I know that the following doesn't work, unfortunately:
// in my main index.js
import customFunc from `${process.env.PATH}/index.js`;
But what can I do? Perhaps something in Webpack?