【发布时间】: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