What I'm trying to achieve is to use dynamically created object in webpack config in a typescript script project (that uses esnext module syntax like import, export, dynamic import())
i.e. something like below (in DefinePlugin)
File - webpack.config.js
const productA = require("./<path>/ProductA");
const productB = require("./<path>/ProductB");
let product;
switch(process.env.PRODUCT_TYPE) {
case 'ProductA':
product = new ProductA();
break;
case 'ProductB':
product = new ProductB();
break;
default:
console.log("ERROR - Incorrect product type")
process.exit(-1);
}
...
...
{
entry: './src/entry.ts',
module: {
rules: [{
test: /\.tsx?$/,
use: 'ts-loader'
}]
},
...
...
plugins: [
new webpack.DefinePlugin({
productType: () => {
return product;
}
})
]
}
Script - DynamicLoad.ts
let product = productType();
product.run();
But, the problem I'm having is with esnext syntax types i.e. ProductA and ProductB classes here uses esnext syntax like import, export and implements keywords. So, webpack throws error when imported these classes into the webpack.config.js files.
So, is there a way to make webpack.config.js understand the esnext syntax?
Different workarounds tried and failed
- Use babel
babel supports imports, export and dynamic import() syntax. So, followed How can I use ES6 in webpack.config.js? and tried with babel (i.e. webpack.config.babel.js)
Issue: But, with this the errors I faced:
- babel not able to identify implements keyword.
- couldn't find .css module (my webpack has css-loader and style-loader)
- webpack in typescript format
- Webpack support typescript formatted config i.e. webpack.config.ts
- Ref - https://webpack.js.org/configuration/configuration-languages/#root
Issue: But, the issue with this is webpack.config.ts needs module type of commonJS whereas my project uses esnext. So, many syntax identification errors are generated.
So, is there any way for me to achieve this in webpack?