我正在尝试测试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
中。当我打开该文件时,尽管它是未使用的导出,但秘密字符串仍在其中。有什么方法可以阻止它包含在最终捆绑包中?
好,所以我知道了。我需要安装软件包@babel/core
,@babel/preset-env
和babel-loader
作为dev-dependencies,并将用于处理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代码摇晃。 "moduleResolution": "node"
解决了一个错误,该错误是某些模块无法解决的错误。