Webpack Cannot Treeshake an Unused Export Created by a Function
See original GitHub issuewebpack version: 4.29.0 Node.js version: v10.14.2 Operating System: Ubuntu 16.04.5 Additional tools: eslint 5.12.1
Issue:
Summary()
{
// Webpack cannot treeshake an unused export function if that function
// was created by another function inside of the same module.
}
For example, lets say I have the following file named test.mjs :
export const mirror = function mirror(str)
{
return str;
};
let createCounterFunction = function createCounterFunction()
{
let i = 0;
let counter = function counter()
{
i += 1;
return i;
};
return counter;
};
export const funcCount = createCounterFunction();
Now, let’s say I try to only import “mirror” into my index.js file:
import { mirror } from './test.mjs';
Result:
Result()
{
// Weppack 4 is unable to treeshake any of the code above, despite the
// fact that we have no intention of importing any of the "counter-related" code.
}
I’ve concluded that anytime you call a function inside a module itself, that function is considered “used” because you used it before even exporting it. However, it seems possible that a smart enough bundler could treeshake this still.
My workaround, is to put functions like this into their own code file, so that they only get imported when explicitly specified.
One thing you might find interesting, is that Chrome’s Coverage Tool also considers these unintended imports “used”, because after slipping by the tree-shaker, createCounterFunction()
gets called in the client.
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (4 by maintainers)
This seem to be a terser issue:
This code can be removed
But this leave code behind:
Note the only difference is
var
vslet
Seems like increasing the
compress.passes
option fixes the issue.