Babel編譯報錯:var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {

場景: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 example.js -o compiled.js

# 整個目錄轉碼
# --out-dir 或 -d 參數指定輸出目錄
$ babel src --out-dir lib
# 或者
$ babel src -d lib

# -s 參數生成source map文件
$ babel src -d lib -s

 使用 babel命令 將 index.js 文件 編譯輸出到 dist 目錄,並生成對應的 source map 文件。 

babel index.js -s -d dist

與君共勉:再牛逼的夢想,也抵不住傻逼般的堅持! 

發佈了84 篇原創文章 · 獲贊 64 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章