Skip to main content

Upgrade Babel For React TypeScript Project

无意间发现 TypeScript 在 4.9 的版本出了一个非常好用的语法糖:satisfies,当我在项目中准备用的时候,发现 babel 版本不支持这个语法,因为我之前是用了babel-preset-react-app, 而这个类库已经很久没有更新了。

所以需要重新为项目配置 babel 编译,整个项目涉及的技术栈是 React,TypeScript,Webpack5,仅面向桌面 web 端。

安装 babel 相关库

pnpm add @babel/core @babel/plugin-transform-runtime @babel/preset-env @babel/preset-react @babel/preset-typescript @babel/runtime babel-loader -D

更新babel.config.json配置

babel.config.json
{
"sourceType": "unambiguous",
"presets": [
"@babel/preset-env",
"@babel/preset-typescript",
["@babel/preset-react", { "runtime": "automatic" }]
],
"plugins": [["@babel/plugin-transform-runtime", { "corejs": false }]],
"targets": {
"node": "20"
}
}

更新 browserlist 配置

由于仅面向桌面端,所以通过工具最终选择了以下浏览器配置:

package.json
"browserslist": [
"> 2%",
"Firefox ESR"
],

更新前编译耗时和文件大小:

Entrypoints:
vendor (990 KiB)
vendor.d7a16263.js
index (466 KiB)
css/index.e90bb441.css
index.1c6450b4.js
webpack 5.74.0 compiled with 2 warnings in 39258 ms

更新后:

Entrypoints:
vendor (972 KiB)
vendor.1b6051b3.js
index (332 KiB)
css/index.6a831ec4.css
index.67d1688b.js
webpack 5.74.0 compiled with 2 warnings in 19504 ms