-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
Description
Bug report
What is the current behavior?
Dead code eliminator for constant expression doesn't handle "return early" if statements.
If the current behavior is a bug, please provide the steps to reproduce.
git clone git@gist.github.com:38b17bb4757ddab9f65efc3bd4e3c083.gitnpm installnpm run build:dev
After run you can see that a new chunk was created and the expression (await import('./module')).getSomething(); is parsed by webpack.
async function main() {
if (true) { // it might be a result of expression with `DefinePlugin`
return;
} else {
// this expression is NOT parsed and the new chunk is NOT created
// (await import('./module')).getSomething();
}
// this expression is parsed and the new chunk is created
(await import('./module')).getSomething();
}But if you comment this line and uncomment this one a chunk will not be created.
From #16672
However, this case is just a simple example of what can pre dead code elimination can achieve.
There are still a lot of scenarios not covered.
- Per File level optimization, like if-return.
export const treeShakingTestAsync = async () => {
console.log('treeShakingTestAsync');
const { foo } = await import(/* webpackChunkName: "bundle_pc" */ './pc');
console.log(foo);
// Code wont't be reached after if_return, but still get to be bundled, and Baz get to be bundled as well, due to splitchunk.
if (false) {
return;
}
const { Baz } = await import(/* webpackChunkName: "bundle_mobile" */'./mobile');
console.log(Baz);
};- unused exports
export const treeShakingTestAsync = async () => {
console.log('treeShakingTestAsync');
const { foo } = await import(/* webpackChunkName: "bundle_pc" */ './pc');
console.log(foo);
};
export const unusedExport = async () => {
console.log('unusedExport');
// this never be refered from entry.
const { Baz } = await import(/* webpackChunkName: "bundle_mobile" */ './mobile');
console.log(Baz);
};What is the expected behavior?
No chunk created in both cases since they both are "inaccessible".
I'd say that this pattern (return early) is quite common so it was surprised that it is not handled so far.
Of course it might be easily "fixed" with a workaround by placing the code to else statement, but I think it would be better to have handling of this in webpack.
Other relevant information:
webpack version: 5.54.0
Node.js version: v14.16.0
Operating System: win10 x64
Additional tools: none