babel 配置问题
//babel.config.js
直接引入 `import 'core-js/stable'` 和 `import 'regenerator-runtime/runtime'` 会有以下影响:
1. 影响打包体积
```javascript
// 这样引入会导入所有 polyfill
import 'core-js/stable'
import 'regenerator-runtime/runtime'
```
- 相当于设置 `useBuiltIns: 'entry'`
- 会引入所有的 polyfill,而不是按需引入
- 显著增加打包体积
2. 与 `useBuiltIns: 'usage'` 冲突
```javascript
// babel.config.js
module.exports = {
presets: [
['@vue/cli-plugin-babel/preset', {
useBuiltIns: 'usage', // 这个配置会与手动引入冲突
corejs: 3
}]
]
}
```
推荐做法:
1. 使用 babel 配置自动处理
```javascript
// babel.config.js
module.exports = {
presets: [
['@vue/cli-plugin-babel/preset', {
useBuiltIns: 'usage', // 按需引入
corejs: 3
}]
]
}
```
2. 移除手动引入
```javascript
// 删除这些手动引入
// import 'core-js/stable'
// import 'regenerator-runtime/runtime'
```
3. 如果确实需要全量引入,修改配置
```javascript
// babel.config.js
module.exports = {
presets: [
['@vue/cli-plugin-babel/preset', {
useBuiltIns: 'entry', // 改为 entry 模式
corejs: 3
}]
]
}
```
对比示例:
1. 手动引入(不推荐)
```javascript
// main.js
import 'core-js/stable'
import 'regenerator-runtime/runtime'
// 会导入所有 polyfill,包体积大
```
2. 自动按需引入(推荐)
```javascript
// babel.config.js
module.exports = {
presets: [
['@vue/cli-plugin-babel/preset', {
useBuiltIns: 'usage',
corejs: 3
}]
]
}
// main.js
// 不需要手动引入,babel 会自动处理
```
3. 实际效果对比
```javascript
// 使用手动引入或 entry 模式
// 打包后可能包含大量未使用的 polyfill
bundle.js: 500KB
// 使用 usage 模式
// 只包含实际使用的 polyfill
bundle.js: 200KB // 体积明显减小
```
最佳实践建议:
1. 删除手动引入的代码
- 移除 `import 'core-js/stable'`
- 移除 `import 'regenerator-runtime/runtime'`
2. 使用 babel 配置
```javascript
module.exports = {
presets: [
['@vue/cli-plugin-babel/preset', {
useBuiltIns: 'usage',
corejs: 3,
targets: {
browsers: ['> 1%', 'last 2 versions', 'not dead']
}
}]
]
}
```
3. 定期检查打包体积
- 使用 webpack-bundle-analyzer 分析
- 确保没有不必要的 polyfill
4. 根据实际需求调整
- 如果确实需要全量 polyfill,使用 entry 模式
- 否则坚持使用 usage 模式
这样可以:
- 优化打包体积
- 提高加载性能
- 保持代码整洁
- 避免重复引入