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

使用require导入Google Gemini库时遇‘Can't find variable: require’错误求助

解决require导入Google Gemini库时的"Can't find variable: require"错误

问题原因

require是Node.js专属的CommonJS模块语法,浏览器环境默认不支持,如果你的代码在浏览器里运行,就会触发这个错误。另外,如果你的Node.js项目配置了ES模块(package.json里有"type": "module"),也会无法识别require。

解决方案

情况1:在浏览器环境中使用

改用ES模块的import语法:

import { GoogleGenerativeAI } from "@google/generative-ai";

同时要确保:

  • 项目的package.json中添加"type": "module"(如果是用构建工具的项目)
  • 或者直接通过CDN引入库:
<script type="module">
  import { GoogleGenerativeAI } from 'https://esm.sh/@google/generative-ai';
  // 后续业务代码
</script>

情况2:在Node.js环境中使用

  • 先确认已经安装了库:
npm install @google/generative-ai
  • 如果项目是ES模块(package.json有"type": "module"),同样用import语法;如果要继续用require,删除package.json里的"type": "module",让项目默认使用CommonJS模块规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 07:47:32