场景:Babel 打包编译带有 async 语法的代码,打包编译之后的代码无法运行。
报错: 运行打包之后的代码,报错如下
var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
^
ReferenceError: regeneratorRuntime is not defined
解决办法:async 是 es7 的特性,Babel 支持对 es6 特性的编译,Babel 在将 async 转 generator function 时,需要安装插件(Babel 的运行环境 和 Babel 插件的编译运行环境)
npm i babel-runtime babel-plugin-transform-runtime -D
配置 .babelrc 文件
{
"plugins": [
[
"transform-runtime", {
"polyfill": false,
"regenerator": true
}
]
]
}
重新打包之后,打包之后的代码能够完美运行!
附:Babel 基础用法
# 转码结果输出到标准输出
$ babel example.js
# 转码结果写入一个文件
# --out-file 或 -o 参数指定输出文件
$ babel example.js --out-file compiled.js
# 或者
$ babel exa