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

Vue组合式API项目用@vue/apollo-composable报react解析错误

解决Vue3 Composition API + Apollo Client的"Could not resolve 'react'"错误

核心原因

@apollo/client包内置了React框架的绑定代码,直接从根路径导入时会触发加载React相关模块,而Vue项目未安装React依赖,导致Vite运行/打包报错。

解决方案

1. 导入Apollo Client核心模块(推荐)

修改apollo/index.ts,从@apollo/client/core导入核心组件,避免加载React相关代码:

import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client/core'

const httpLink = new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL });

export default new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
})

2. 配置Vite排除React依赖(备选)

如果上述方法仍有问题,在vite.config.ts中把React标记为外部依赖,让Vite跳过解析:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  build: {
    rollupOptions: {
      external: ['react', 'react-dom']
    }
  }
})

Vue Apollo优雅使用方案

你当前使用@vue/apollo-composable的provide(DefaultApolloClient)是Composition API下的标准用法,以下是完整最佳实践:

  1. 建议使用@vue/apollo-composable稳定版(如^4.0.0正式版),避免beta版本的潜在问题;
  2. 组件内查询示例:
<script setup lang="ts">
import { useQuery } from '@vue/apollo-composable'
import gql from 'graphql-tag'

const { result, loading, error } = useQuery(gql`
  query GetPosts {
    posts {
      id
      title
    }
  }
`)
</script>

<template>
  <div v-if="loading">加载中...</div>
  <div v-else-if="error">{{ error.message }}</div>
  <ul v-else>
    <li v-for="post in result?.posts" :key="post.id">{{ post.title }}</li>
  </ul>
</template>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:25:15