Babel
安装及命令行的使用
npm i @babel/core // 核心
npm i @babel/cli // cli 工具
npx babel src --out-dir dist // 转化并输出
npm i @babel/plugin-transform-arrow-functions //转化箭头函数的插件
npx babel src --out-dir dist --plugins=@babel/plugin-transform-arrow-functions // 使用插件转化并输出
npm i @babel/preset-env
npx babel src --out-dir dist --presets=@babel/preset-env // 使用插件转化并输出
原理
babel 可以看成一个JS的编译器
- Parsing
- Transformation
- Code Generation
webpack使用
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
exclude: /(node_modules|bower_components)/, // 防止重复的polyfill 导致冲突, 不使用babel
options: {
presets: ['@babel/preset-env'], // 多个插件的组合,代替 plugins
// 通过 target 指定适配目标浏览器
// plugins: [
// "@babel/plugin-transform-arrow-functions"
// ]
}
}
}
抽取配置文件
- .babelrc.json
早期 - babel.config.json
7 以后
// babel.config.js
module.exports = {
presets: [
'@babel/preset-env'
]
}
Polyfill
概念
使用
配置
module.exports = {
presets: [
[
'@babel/preset-env', {
useBuiltIns: false // pollyfill使用 false usage entry
}
]
]
}
useBuiltIns
- false
不使用- usage
只填充代码中使用的- entry
所有目标浏览器需要的
需要在webpack的入口文件引入包:
import 'core/js/stable';
import 'regenerator-runtime/runtime';
// babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env', {
//target: ["chrome 90"], // 兼容目标浏览器
useBuiltIns: usage, // pollyfill使用 false usage entry
corejs: 3 // 指定使用的 corejs的版本, 默认2
}
]
],
}
@babel/plugin-transform-runtime
和 useBuiltIns 二选一
// babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env', {
}
]
],
plugins: [
["@babel/plugin-transform-runtime", {
corejs: 3 // 需要安装 @babel-corejs3
}
] // 和 useBuiltIns 二选一
]
}
Babel 对 React 的支持
Babel对TS的支持
使用 ts-loader
// webpack.config.js
module: {
rules: [
{
test: /\.ts$/,
use: "ts-loader"
}
],
}
使用 babel-loader
// babel.config.js
module.exports = {
presets:[
[
'@babel/preset-env', { //polyfill
useBuiltIns: 'usage',
corejs: 3
}
],
["@babel/preset-typescript"]
]
}
// webpack.config.js
module: {
rules: [
{
test: /\.ts$/,
use: 'babel-loader'
}
],
}
最佳实践
babel-loader
- polyfill
- 不做类型检查
ts-loader
- 类型检查
结论
- tsc
类型检查 - babel-loader
编译
// package.json
"scripts":{
"build": "npm run type-check & webpack --config we.config.js",
"type-check": "tsc --noEmit",
"type-check-watch": "tsc --noEmit --watch"
}