You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Babel转换async函数异常导致regeneratorRuntime未定义报错如何解决?

错误原因

你代码中使用了async/await语法,@babel/preset-env默认仅完成语法转换,不会自动注入ES6+新增API的polyfill实现。async/await转译后的代码依赖regeneratorRuntime全局变量,但当前配置未引入该变量的对应实现,因此运行时会抛出未定义错误。

解决方案

推荐使用@babel/plugin-transform-runtime实现polyfill按需注入,不会污染全局作用域,同时可复用辅助代码减小打包体积,配置步骤如下:

  • 安装所需依赖
    开发依赖:
    npm install @babel/plugin-transform-runtime -D
    
    生产依赖:
    npm install @babel/runtime @babel/runtime-corejs3
    
  • 修改webpack中babel-loader配置
    {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
            loader: 'babel-loader',
            options: {
                presets: [
                    ['@babel/preset-env', {
                        // 可根据项目兼容需求指定目标浏览器,减少多余polyfill注入
                        targets: "> 0.25%, not dead"
                    }]
                ],
                plugins: [
                    ['@babel/plugin-transform-runtime', {
                        corejs: 3 // 启用corejs3提供polyfill,自动包含regeneratorRuntime实现
                    }]
                ]
            }
        }
    }
    

如果是小型项目也可选择快速修复方案,直接在项目入口文件的首行引入regenerator-runtime:

import 'regenerator-runtime/runtime'

该方案实现简单但会向全局注入变量,适合不需要考虑全局污染的场景使用。


内容的提问来源于stack exchange,提问作者user16336116

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:15:04