use*_*473 5 bundler typescript webpack tree-shaking
我正在尝试测试 Webpack 的摇树功能,但它似乎不起作用。
这是我的文件:
index.tsimport { good } from './exports';
console.log(good);
Run Code Online (Sandbox Code Playgroud)
exports.tsexport const good = 'good';
export const secret = 'iamasecret';
Run Code Online (Sandbox Code Playgroud)
tsconfig.json{}
Run Code Online (Sandbox Code Playgroud)
webpack.config.tsimport { 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;
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
当我运行npx webpack它时,它会将文件捆绑到dist/main.js. 当我打开那个文件时,尽管它是一个未使用的导出,但秘密字符串就在那里。有什么方法可以阻止它包含在最终捆绑包中?
好的,所以我想通了。我需要安装包@babel/core、@babel/preset-env和babel-loader作为开发依赖项,并将处理 TypeScript 文件的 Webpack 配置规则更改为:
{
test: /\.tsx?$/,
use: ['babel-loader','ts-loader'],
exclude: /node_modules/,
},
Run Code Online (Sandbox Code Playgroud)
接下来,我创建了一个.babelrc包含以下内容的文件:
{
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
]
]
}
Run Code Online (Sandbox Code Playgroud)
最后,我更改/添加了以下几行到我的tsconfig.json下compilerOptions:
"module": "es6",
"moduleResolution": "node",
Run Code Online (Sandbox Code Playgroud)
使用babel-loader、设置.babelrc配置和使用"module": "es6",允许我的 TypeScript 代码被摇树。"moduleResolution": "node"修复了我收到某些模块无法解决的错误的问题。
| 归档时间: |
|
| 查看次数: |
1946 次 |
| 最近记录: |