I am trying to get the 2 webpack features to work together.
The first is the exclusion of code when introducing it within an if (process.env.NODE_ENV === 'development') { block.
The second is the exclusion of unused imported modules.
The issue is that these two operations seem to be happening in the opposite order, so as a result if we have code that looks something like this:
import Module from 'module';
-----------------------------------
if (process.env.NODE_ENV === 'development') {
use(Module);
}
The code-block may be removed, but the imported module is present in the resulting bundle.
Is there some way to run the check for an unused import after the if-block is removed, or am I doing something wrong and if so what is the correct way to not import a module in a production build?
Hopefully there is a cleaner solution using the 2 features above, but if someone else runs into this question and it isn't answered yet, you can write a short loader that will achieve this goal:
module.exports = function (source) {
return this.getOptions().isDevelopment ? source : source.replace(/\/\* *dev:start ?\*\/[\s\S]*?\* *dev:end *\*\//g, '');
};
You can then place it as the first loader to proccess your files (meaning the last loader of the array):
{
test: /\.(js|ts|jsx|tsx)?$/,
use: [
{
loader: path.resolve('./remove-dev.loader.js'),
options: { isDevelopment },
},
],
},
And then you can utilize it in the code, turning it into something like this:
import Module from 'module';
-----------------------------------
/* dev:start */
use(Module);
/* dev:end */