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

Vite构建React应用时,Babel编译JS文件遇require未定义错误

问题原因与解决办法

问题原因

你使用@babel/preset-env编译代码时,Babel默认会将代码转换为CommonJS模块格式,因此自动插入了require和exports相关的模块化代码。但浏览器原生环境并不支持CommonJS的require语法,所以运行时会抛出Uncaught ReferenceError: require is not defined错误。

解决办法

需要明确指定Babel输出浏览器可直接识别的模块格式,以下两种方式任选其一:

方式1:修改命令行参数

在编译命令中添加--modules参数,指定输出格式:

  • 如果需要兼容全局变量、CommonJS、AMD等多种环境,选umd格式:
npx babel widget/scripts/api.js --out-dir widget/api --presets=@babel/preset-env --no-babelrc --modules=umd
  • 如果你的Vite项目支持直接导入ES模块,选es格式:
npx babel widget/scripts/api.js --out-dir widget/api --presets=@babel/preset-env --no-babelrc --modules=es

方式2:使用Babel配置文件(更便捷)

创建babel.config.json配置文件,预设目标环境和模块格式:

{
  "presets": [
    ["@babel/preset-env", {
      "modules": "umd", // 或"es",按需选择
      "targets": {
        "browsers": "> 0.25%, not dead"
      }
    }]
  ]
}

之后简化编译命令(去掉--no-babelrc和--presets参数):

npx babel widget/scripts/api.js --out-dir widget/api

额外说明:你的原文件已是ES5语法,@babel/preset-env主要作用是处理模块格式而非语法降级,选择合适的模块格式是解决报错的核心。

内容的提问来源于stack exchange,提问作者A.Burdonskaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 14:48:23