apollo - 如何在 SvelteKit 中初始化 ApolloClient 以同时在 SSR 和客户端上工作
问题描述
我试过但没有用。出现错误:评估 SSR 模块 /node_modules/cross-fetch/dist/browser-ponyfill.js 时出错:
<script lang="ts">
import fetch from 'cross-fetch';
import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";
const client = new ApolloClient({
ssrMode: true,
link: new HttpLink({ uri: '/graphql', fetch }),
uri: 'http://localhost:4000/graphql',
cache: new InMemoryCache()
});
</script>
解决方案
使用 SvelteKit,CSR 与 SSR 的主题以及应该在何处获取数据比使用其他有点“相似”的解决方案更深入一些。下面的指南应该可以帮助您连接一些点,但首先需要说明几件事。
要定义服务器端路由,请在目录树的任何位置创建一个.js
扩展名为的文件。src/routes
该.js
文件可以包含所需的所有导入语句,而无需将它们引用的 JS 包发送到 Web 浏览器。
@apollo/client
非常大,因为它包含依赖react
项。@apollo/client/core
相反,即使您将 Apollo 客户端设置为仅在服务器端使用,您也可能需要考虑仅导入,如下面的演示所示。这@apollo/client
不是 ESM 包。请注意它是如何导入下面的,以便项目使用节点适配器成功构建。
尝试执行以下步骤。
- 创建一个新的 SvelteKit 应用程序并在 SvelteKit 设置向导的第一步中选择“SvelteKit 演示应用程序”。回答“使用 TypeScript?” 问题
N
以及之后的所有问题。
npm init svelte@next demo-app
cd demo-app
- 相应地修改
package.json
。可以选择检查所有软件包更新npx npm-check-updates -u
{
"name": "demo-app",
"version": "0.0.1",
"scripts": {
"dev": "svelte-kit dev",
"build": "svelte-kit build --verbose",
"preview": "svelte-kit preview"
},
"devDependencies": {
"@apollo/client": "^3.3.15",
"@sveltejs/adapter-node": "next",
"@sveltejs/kit": "next",
"graphql": "^15.5.0",
"node-fetch": "^2.6.1",
"svelte": "^3.37.0"
},
"type": "module",
"dependencies": {
"@fontsource/fira-mono": "^4.2.2",
"@lukeed/uuid": "^2.0.0",
"cookie": "^0.4.1"
}
}
- 相应地修改
svelte.config.js
。
import node from '@sveltejs/adapter-node';
export default {
kit: {
// By default, `npm run build` will create a standard Node app.
// You can create optimized builds for different platforms by
// specifying a different adapter
adapter: node(),
// hydrate the <div id="svelte"> element in src/app.html
target: '#svelte'
}
};
src/lib/Client.js
使用以下内容创建文件。这是 Apollo 客户端设置文件。
import fetch from 'node-fetch';
import { ApolloClient, HttpLink } from '@apollo/client/core/core.cjs.js';
import { InMemoryCache } from '@apollo/client/cache/cache.cjs.js';
class Client {
constructor() {
if (Client._instance) {
return Client._instance
}
Client._instance = this;
this.client = this.setupClient();
}
setupClient() {
const link = new HttpLink({
uri: 'http://localhost:4000/graphql',
fetch
});
const client = new ApolloClient({
link,
cache: new InMemoryCache()
});
return client;
}
}
export const client = (new Client()).client;
src/routes/qry/test.js
使用以下内容创建。这是服务器端路由。如果 graphql 模式没有double
指定不同的查询、输入和输出的函数。
import { client } from '$lib/Client.js';
import { gql } from '@apollo/client/core/core.cjs.js';
export const post = async request => {
const { num } = request.body;
try {
const query = gql`
query Doubled($x: Int) {
double(number: $x)
}
`;
const result = await client.query({
query,
variables: { x: num }
});
return {
status: 200,
body: {
nodes: result.data.double
}
}
} catch (err) {
return {
status: 500,
error: 'Error retrieving data'
}
}
}
- 将以下内容添加到标签内的文件
load
功能中。routes/todos/index.svelte
<script context="module">...</script>
try {
const res = await fetch('/qry/test', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
num: 19
})
});
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
- 最后执行
npm install
和npm run dev
命令。在您的 Web 浏览器中加载该站点,并在您将鼠标悬停在TODOS
导航栏上的链接上时查看正在从客户端查询的服务器端路由。在控制台的网络选项卡中,请注意由于 Apollo实例是单例test
的,因此每秒和后续请求的路由响应要快多少。client
推荐阅读
- playframework - 将 Play 项目移植到 Lagom
- kotlin - 将 url 的内容添加到 Ktor 中的 respondText
- java - log4j 1.x 中错误方法的区别
- python - Tkinter,更改按钮及其命令
- c - 卡在一个 for 循环中,用 C 语言将值输入到一个数组中
- java - 使用 Cucumber 为每个正在运行的线程创建一个 TestNG 运行器类
- javascript - 如何在 restify 7.x 中使用自定义错误选项创建自定义错误?
- prolog - 序言中的这个或/和那个事实
- angular - 角路由器链接活动嵌套菜单
- react-native - Panresponder 可以继承 Touchable 触摸事件吗?