I want to create build that will, based on env variable, include just specific components in the bundle.
For example when I import component like this:
import Module1 from '@/components/Module1'
I want the path to actually be converted so that imports looks like this:
import Module1 from '@/components/brands/' + process.env.APP_BRAND + 'Module1'
Now I don't want to do this for all imports, just for certain ones (eg. modules that have branded version), so maybe I'd like to prefix import path with something like !brand!
which will be indicator to apply path transform.
So above logic should executed only for import paths such as:
import Module1 from '!brand!@/components/Module1'
And if process.env.APP_BRAND
is falsy then I just want to stick to the original import (eg. just remove !brand!
prefix from the path).
So the important aspect is that I want this to be done at build time so that Webpack can statically analyze modules and create optimized build. Is this possible to do? I suppose I need to somehow add this path transformation logic but how should I do that? Should I create a loader, plugin or is there an existing solution?
I am using Webpack 5.
Webpack provides a module resolve functionality that you can use here. Read the docs here. As an example, in your case, you can do this:
const path = require('path');
module.exports = {
resolve: {
alias: {
'@/components/Module1': path.join(
__dirname,
process.env.APP_BRAND
? '@/components/brands/' + process.env.APP_BRAND + 'Module1'
: '@/components/Module1')
}
},
};
Note that, here you would pass environment variable to your Webpack process (aka Node.js process) and make decision accordingly. Also, your resolve module must be absolute path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With