Background
webpack v5
webpack mode: production
webpack optimization.minimize: false for test about tree shaking not dead_code or unused code
vanilla js
sideEffects: false in package.json
Problem
// test.js
export const A = () => {
const a = 10;
console.log("a : ", a);
};
export const B = () => {
const a = 10;
console.log("a : ", a);
};
export const C = () => {
const a = 10;
console.log("a : ", a);
};
export const D = () => {
const a = 10;
console.log("a : ", a);
};
// main.js
import { A, B } from "./test";
A();
B();
I imported only A, B but the result of bundling with webpack is this below
/******/ (() => {
// webpackBootstrap
/******/ "use strict";
var __webpack_exports__ = {}; // CONCATENATED MODULE: ./src/test.js
const A = () => {
const a = 10;
console.log("a : ", a);
};
const B = () => {
const a = 10;
console.log("a : ", a);
};
const C = () => {
const a = 10;
console.log("a : ", a);
};
const D = () => {
const a = 10;
console.log("a : ", a);
}; // CONCATENATED MODULE: ./src/main.js
A();
B();
/******/
})();
As you can see, C, D is also defined.
Why does tree shaking not work in this case ?
But, this case works
?src
? ?test-dir
? ? ?a.js
? ? ?b.js
? ? ?c.js
? ? ?index.js
? ?main.js
// test-dir/index.js
export { A } from "./a";
export { B } from "./b";
export { C } from "./c";
// main.js
import { A, B } from "./test-dir";
A();
B();
Bundle result
/******/ (() => { // webpackBootstrap
/******/ "use strict";
var __webpack_exports__ = {};
;// CONCATENATED MODULE: ./src/test-dir/a.js
const A = () => {
const a = 10;
console.log("a : ", a);
};
;// CONCATENATED MODULE: ./src/test-dir/b.js
const B = () => {
const a = 10;
console.log("a : ", a);
};
;// CONCATENATED MODULE: ./src/main.js
A();
B();
/******/ })();
Why does tree shaking work in this case ?