When I tried tree shaking with webpack, I found that sometimes it didn't work properly.
I want to known why tree shaking not work in first one?
// utils.js
var sum = (a, b) => {
return a + b;
};
// first case: webpack not work in this case
var Cache = (function () {
function Cache() {}
Cache.prototype.b = function () {};
Cache.prototype.a = function () {};
return Cache;
})();
// second: cache will be tree shaking
var Cache = (function () {
function Cache() {}
Cache.prototype.a = function () {};
return Cache;
})();
export { Cache, sum };
// index.js
import { sum } from "./utils";
console.log("hello world", global.test);
the first one build result is:
(() => {
"use strict";
!(function () {
function o() {}
(o.prototype.b = function () {}), (o.prototype.a = function () {});
})(),
console.log("hello world", 3);
})();
the second is:
(() => {
"use strict";
console.log("hello world", 3);
})();
this is my package.json
// package.json
{
"name": "webpack-tree-shaking-demo",
"version": "1.0.0",
"description": "A demo project to demonstrate webpack tree shaking with TypeScript",
"main": "./dist/main.js",
"module": "./dist/main.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/main.js",
"require": "./dist/main.js",
"types": "./dist/index.d.ts"
}
},
"scripts": {
"build": "webpack --mode production",
"build:dev": "webpack --mode development",
"start": "webpack serve --mode development --open",
"tsc": "tsc"
},
"keywords": [
"webpack",
"tree-shaking",
"typescript"
],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.98.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
}
}
this is my webpack config
// webpack.config.js
const path = require("path");
module.exports = (env, argv) => {
return {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
},
resolve: {
extensions: [".js"],
}
};
};
Maybe because the function may have side effects, so there is no tree shaking? But why the second one can be tree shaken