React-Vite环境使用@octokit/core调用GitHub API时遇类型错误求助
解决React-Vite中使用@octokit/core出现
import_stream.default.Readable is undefined的错误 这个错误是因为@octokit/core依赖的内部模块用到了Node.js的stream API,但浏览器环境本身不支持该API,而Vite默认不会自动为浏览器polyfill Node.js核心模块,导致找不到Readable对象。
解决步骤如下:
安装Node.js核心模块的polyfill插件
执行以下命令安装依赖:npm install vite-plugin-node-polyfills --save-dev配置Vite启用polyfill
修改项目根目录下的vite.config.js文件,添加插件配置:import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import { nodePolyfills } from 'vite-plugin-node-polyfills'; export default defineConfig({ plugins: [ react(), nodePolyfills({ // 明确需要polyfill的模块 include: ['stream'], // 同时全局polyfill Buffer和process,避免后续可能出现的其他Node API缺失问题 globals: { Buffer: true, process: true, }, }), ], });(可选)更新@octokit/core版本
如果你使用的是较旧版本的@octokit/core,可能存在浏览器兼容性问题,执行以下命令更新到最新版:npm update @octokit/core
完成以上步骤后,重启Vite开发服务器,错误应该就能解决了。
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

