• babel 编译后的在 node 环境中运行提示 "regeneratorRuntime is not defined"


    babel 使用 @babel/preset-env 预设 编译后的代码在 node 环境中运行提示 "regeneratorRuntime is not defined",这个错误是 bableasync/await 转换时产生的。

    babel@babel/preset-env 有这样一句话

    Since one of the original goals of preset-env was to help users easily transition from using preset-latest, 
    it behaves similarly when no targets are specified: preset-env will transform all ES2015-ES2020 code to be ES5 compatible.
    

    如果我们没有指定目标运行环境的话,会将我们所有的代码都转换成 ES5, 所有我们代码中如果使用了 async/await 就会进行ES5转换,经 google 之后,
    发现 babel 转换 async/await 主要时通过 @babel/plugin-transform-async-to-generator
    插件来实现的。打开这个插件介绍可以看到:

    NOTE: This plugin is included in @babel/preset-env In Babel 7, transform-async-to-module-method was merged into this plugin
    

    这个插件在 Babel 7 中已经内置到了 @babel/preset-env, 那么我们是不是可以告诉 @babel/preset-env 不要使用 @babel/plugin-transform-async-to-generator 插件帮
    我们编译就好了。

    解决方法一

    修改 babel 的配置 .babelrc.json 为:

    {
      "presets": [
        [
          "@babel/preset-env",
          {
            "exclude": ["@babel/plugin-transform-regenerator"]
          }
        ]
      ],
      "plugins": []
    }
    

    这样配置后重新打包就会发现不会有 'regeneratorRuntime is not defined' 的错误了。

    这可以解决,但是我去看 @babel/preset-env 的文档可以发现 Optionstargets
    可以指定 目标环境 那么我就可以把 targets 指定为高一些即可。

    解决方法二

    指定代码的运行环境,修个 .babelrc.json 为:

    {
      "presets": [
        [
          "@babel/preset-env",
          {
            "targets": {
              "chrome": "80",
              "node": "14"
            }
          }
        ]
      ]
    }
    

    我这里把 chrome 环境指定到了 80 以上,node 环境指定到了 14 以上,
    这样根据自己的项目实际情况来指定,进而解决了这个问题。

    建议使用方法二来解决这个问题。

    参考

    @babel/preset-env

    @babel/preset-env Options

    @babel/plugin-transform-async-to-generator

    avoiding the import “regenerator-runtime/runtime”

  • 相关阅读:
    nginx负载均衡
    mysqld: Out of memory Centos 创建swap分区解决
    redis 基本命令
    查看日志常用命令
    StringIO和BytesIO
    paramiko初识
    微信小程序-drf登录认证组件
    微信小程序之模块化--module.exports
    celery 定时任务报错一
    微信小程序跨页面传值
  • 原文地址:https://www.cnblogs.com/taohuaya/p/14771234.html
Copyright © 2020-2023  润新知