
内容声明
本文仅用于技术分享和学习交流,内容不包含任何广告、推广、引流、付费课程或外链信息。所有示例和配置均为技术实践,欢迎参考和自定义。
使用 ts-loader 在构建打包生产代码时面对重重问题,比如 Polyfill 的自动注入等,于是转变为用 Babel 来编译 TypeScript。
安装 webpack 和 TypeScript 所必要的 Babel 依赖:
# Babel & webpack loader
npm install @babel/core @babel/cli @babel/preset-env @babel/preset-typescript babel-loader @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties @babel/plugin-proposal-private-methods @babel/plugin-proposal-object-rest-spread core-js -D
# Babel runtime with corejs3 support
npm install @babel/runtime @babel/runtime-corejs3 -Sbabel.config.jsmodule.exports = function (api) {
api.cache(true);
return {
presets: [
[
"@babel/preset-env",
{
// "usage" 会在代码中按需注入 core-js polyfills (适合应用)
// "entry" 需要手动在入口 import "core-js/stable"; import "regenerator-runtime/runtime";
// 或者把 useBuiltIns 改为 false (不注入 polyfill)
useBuiltIns: false, // 或 "usage" / "entry"
corejs: 3,
// 可以根据需要设置 targets,也可由 browserslist 决定
// targets: { browsers: [">0.2%", "not dead", "not op_mini all"] },
bugfixes: true,
modules: false
}
],
"@babel/preset-typescript"
],
plugins: [
// 推荐用于库,抽出 helper,减少重复代码;如果需要 core-js 注入,配置 corejs 选项
[
"@babel/plugin-transform-runtime",
{
corejs: false, // 或 3 表示把 core-js polyfills 用 runtime 方式注入 (需要 @babel/runtime-corejs3)
helpers: true,
regenerator: true,
version: require("@babel/runtime/package.json").version
}
],
// class fields、private fields 等 (现代 JS 特性)
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-private-methods",
"@babel/plugin-proposal-object-rest-spread"
]
};
};module.exports = {
// ...entry, output 等
module: {
rules: [
{
test: /\.[jt]sx?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
cacheDirectory: true,
cacheCompression: false,
// babel.config.js 会被自动加载
}
}
}
// 其他 loader (CSS、图片等)
]
},
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx", ".json"]
}
// ...plugins, optimization 等
};安装 typescript:
npm install typescript -D配置 tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"lib": ["ES2022", "DOM"],
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
"moduleResolution": "bundler",
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
// 对用 Babel 转译的项目很重要:
"isolatedModules": true,
// 不让 tsc 输出 .js 文件 (Babel 去转译)
"noEmit": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}修改 package.json,添加脚本命令和 Browserslist:
{
"scripts": {
"build:webpack": "webpack --config webpack.config.js"
},
"browserslist": [
">0.2%",
"not dead",
"not op_mini all"
]
}案例: GitHub: new-typescript-project/release/babel
本文章首次编辑于 2020-08-28,最近更新于 2025-11-07。项目代码在 Node.js 16.x 上已测试可稳定运行。
版权声明
本文为原创文章,作者保留版权。转载请保留本文完整内容,并以超链接形式注明作者及原文出处。
作者: 除除
原文: http://blog.mazey.net/1722.html
(完)
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。