webpack tree shaking not working in some case - Stack Overflow

When I tried tree shaking with webpack, I found that sometimes it didn't work properly.I want to

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744742976a4591137.html

相关推荐

  • webpack tree shaking not working in some case - Stack Overflow

    When I tried tree shaking with webpack, I found that sometimes it didn't work properly.I want to

    18小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信