【问题标题】:Webpack tree shaking still bundles unused exportsWebpack 摇树仍然捆绑未使用的导出
【发布时间】:2020-07-28 21:51:33
【问题描述】:

我正在尝试测试 Webpack 的摇树功能,但它似乎不起作用。

这是我的文件:

  • index.ts
import { good } from './exports';
console.log(good);
  • exports.ts
export const good = 'good';
export const secret = 'iamasecret';
  • tsconfig.json
{}
  • webpack.config.ts
import { Configuration } from 'webpack';
import  * as TerserPlugin from "terser-webpack-plugin";
const config: Configuration = {
    mode: 'production',
    entry: './index.ts',
    module: {
        rules: [
          {
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/,
          },
        ],
      },
      resolve: {
        extensions: [ '.tsx', '.ts', '.js' ]
      },
      optimization: {
        usedExports: true,
        minimizer: [new TerserPlugin()],
      }
}
export default config;
  • package.json
{
  "name": "webpacktest",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/terser-webpack-plugin": "^2.2.0",
    "@types/webpack": "^4.41.11",
    "terser-webpack-plugin": "^2.3.5",
    "ts-loader": "^7.0.0",
    "ts-node": "^8.8.2",
    "typescript": "^3.8.3",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11"
  },
  "sideEffects": false
}

当我运行npx webpack 时,它会将文件捆绑到dist/main.js。当我打开该文件时,尽管它是未使用的导出,但秘密字符串仍在其中。有没有办法阻止它包含在最终捆绑包中?

【问题讨论】:

  • 为什么你的“tsconfig.json”是空的?如果您的 ts 被转译成 es 模块,Webpack 能够对此类导入进行 tree-shake。
  • 我没有我需要在那里做的事情(我想)。但是现在,经过一番研究,我发现ts-loader 编译为 CommonJS 模块,而不是 ES 模块。我相信我已经找到了使用 Babel 的解决方案。我会确认一下,然后在这里分享。
  • 好的,如果tsconfig.json 中有"module", "commonjs",我的发现不起作用,这对于我的实际项目是必需的(此处列出的代码只是一个孤立的测试)

标签: typescript webpack bundler tree-shaking


【解决方案1】:

好的,所以我想通了。我需要将包@babel/core@babel/preset-envbabel-loader 安装为开发依赖项,并将用于处理TypeScript 文件的Webpack 配置规则更改为:

    {
        test: /\.tsx?$/,
        use: ['babel-loader','ts-loader'],
        exclude: /node_modules/,
    },

接下来,我创建了一个.babelrc 文件,内容如下:

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "modules": false
            }
        ]
    ]
}

最后,我在tsconfig.json 下的compilerOptions 下更改/添加了以下几行:

"module": "es6",
"moduleResolution": "node",

使用babel-loader,设置.babelrc 配置,并使用"module": "es6",允许我的TypeScript 代码进行tree-shaken。 "moduleResolution": "node" 修复了我收到某些模块无法解决的错误的问题。

【讨论】:

  • 感谢您发布答案,我也很好奇。 :)
猜你喜欢
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
  • 2016-11-17
  • 2019-12-29
  • 2016-12-28
  • 2018-05-27
相关资源
最近更新 更多