node 10.14.1
Babel 7.4.3node
Babel 是一个工具链,主要用于将 ECMAScript2015+版本的代码转换为向后兼容的 Javascript 代码,以便可以运行在当前和旧版本的浏览器或其余环境中。android
- 语法转换 - 垫片支持
Babel 语法转换核心功能,内置 helpers 插件模块,是语法转换的主要辅助工具es6
这是一个很是智能的环境预设模块,根据 env 配置自动 分析查找对应的 helper 和 plugins 进行代码编译转换
基本使用:chrome
presets: [ [ '@babel/preset-env', { targets: { chrome: '77', android: '2', }, debug: true, useBuiltIns: false, }, ], ],
其余参数参考文档配置就行了,这里重点分析一下 useBuiltIns 属性.
targets 可根据文档自行配置,这个比较简单。
debug 调试模式,建议开启,开启以后能够看到 那些 target 使用了那些 plugins 和 polyfill编程
// 开启debug 模式的构建信息 Using targets: { "android": "2", "chrome": "77" } Using modules transform: auto Using plugins: transform-template-literals { "android":"2" } transform-literals { "android":"2" } transform-function-name { "android":"2" } transform-arrow-functions { "android":"2" } ...... ...... Using polyfills with `usage` option: [/Users/weng/Documents/dongsheng/projects/bable/src/app.js] Added following core-js polyfills: es6.object.set-prototype-of { "android":"2" } es6.object.create { "android":"2" } es6.symbol { "android":"2" } es7.symbol.async-iterator { "android":"2" } [/Users/weng/Documents/dongsheng/projects/bable/src/app.js] Added following core-js polyfills: es6.string.includes { "android":"2" } es7.array.includes { "android":"2" } es6.array.of { "android":"2" }
useBuiltIns 属性使用:api
正常状况下,每一个文件都有局部引入自身的 helpers 函数实现,打包后放置在文件的最顶部。
因此存在一个状况,多个文件使用了一样的语法,那么一样的 helpers 会屡次引入。
transform-runtime 就是解决这个问题的。
transform-runtime 为了减小代码量,引入的 helpers 只保留一份
看个栗子:
源代码:浏览器
//app.js import { add } from './add'; function app() { add(1, 2); console.log(Object.assign({}, { ...{ name: 'd' } })); const _a = Array.of(3, 11, 8); } app();
export function add(a, b) { console.log('加法:'); console.log(Object.assign({}, { ...a })); }
// 不启动 transform-runtime 构建后: // 包含了多个一样的 helpers
plugins: ['@babel/plugin-transform-runtime']; // 一样的helpers只加载一次,可是没有 方法api的实现
// corejs设置版本号:2或者3,都会引入非实例方法api的兼容实现 plugins: [ [ '@babel/plugin-transform-runtime', { corejs: 2, }, ], ];
transform-runtime 也是作兼容的:babel
prest-env 影响 语法转换 和 垫片兼容
并且自身还兼容了 默认的 代码转换功能,根据具体 env 分析要使用的 pluginsapp
语法转换 和 垫片兼容 是两个 独立功能,只不过都是 根据 env 来 实现目标转换.async