>[success] # babel -- 初步上手之各种配置@babel/helpers ~~~ 1.回顾一下'babel' 只是一个编译器步骤: 解析(Parsing)AST=》转换(Transformation)需要预设或者插件规则=》生成(Code Generation) 配合上了预设和插件规则的babel也是只是语法层面的转换,当想让其对api层面的转换需要'corejs' 2.像Promise 这类api层面都是corejs,但是像class 这类他实际是语法糖并不是api层面corejs也没有 对其支持,这类就需要'@babel/helpers'每一个语法都可以这样转换为低版本的语法,理论上所有 的语法都可以用低版本的语法来实现。但是只是转换并不能解决所有问题,涉及到某个对象的 api,比如 Array.prototype.find,这种 api 的兼容并不是需要转换语法,而是要在环境中注入我们 实现的 api,也就是 polyfill (垫片)。 3.Babel helpers 函数,同时它提供了 regenerator-runtime,对 generator 和 async 函数进行编译降 级。 ~~~ >[danger] ##### 帮助函数 -- helper ~~~ 1.helper 分为两种: 1.1.一种是注入到 AST 的运行时用的全局函数 1.2.一种是操作 AST 的工具函数,比如变量提升这种通用逻辑 下面图中就是 _classCallCheck 就是 helper 注入的,用 function 和 prototype 实现 class, helper 是在编译时注入 AST 2.下面案例就是使用帮助函数可以看出帮助函数是在生成新的ast 树的时候注入进去 ~~~ * 案例 ~~~ const hoistVariables = require('@babel/helper-hoist-variables').default; cosnt plugin = function () { visitor: { VariableDeclaration(path) { hoistVariables(path.parentPath, (id) => { path.scope.parent.push({ id: path.scope.generateUidIdentifier(id.name) }); return id; }, 'const' ); } } } ~~~ ![](https://img.kancloud.cn/b7/e6/b7e6d00914a14b40f178bfb314275c3f_1065x467.png) [在线转换地址](https://babeljs.io/repl/#?browsers=defaults&build=&builtIns=false&corejs=3.21&spec=false&loose=false&code_lz=MYGwhgzhAECCDeBfIA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=env%2Creact%2Cstage-2&prettier=false&targets=&version=7.17.6&externalPlugins=&assumptions=%7B%7D)