如何在 SvelteKit 中初始化 ApolloClient 以在 SSR 和客户端上工作

Ma3*_*yTa 5 apollo svelte sveltekit

我尝试过但没有成功。出现错误:评估 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>
Run Code Online (Sandbox Code Playgroud)

pha*_*eth 11

对于 SvelteKit,CSR 与 SSR 以及数据获取应该在哪里进行的主题比其他有些“类似”的解决方案要更深一些。下面的指南应该可以帮助您连接一些点,但首先需要说明一些事情。

要定义服务器端路由,请.jssrc/routes目录树中的任意位置创建一个具有扩展名的文件。该.js文件可以包含所需的所有导入语句,而无需将它们引用的 JS 包发送到 Web 浏览器。

@apollo/client相当巨大,因为它包含react依赖项。@apollo/client/core相反,即使您将 Apollo 客户端设置为仅在服务器端使用,您也可能需要考虑仅导入,如下面的演示所示。这@apollo/client不是 ESM 软件包。请注意下面如何导入它,以便使用节点适配器成功构建项目。

尝试执行以下步骤。

  1. 创建一个新的 SvelteKit 应用程序,并在 SvelteKit 设置向导的第一步中选择“SvelteKit 演示应用程序”。回答“使用 TypeScript?” 问题N以及之后的所有问题。
npm init svelte@next demo-app
cd demo-app
Run Code Online (Sandbox Code Playgroud)
  1. 相应修改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"
    }
}
Run Code Online (Sandbox Code Playgroud)
  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'
    }
};
Run Code Online (Sandbox Code Playgroud)
  1. 创建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;

Run Code Online (Sandbox Code Playgroud)
  1. 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'
        }
    }
}

Run Code Online (Sandbox Code Playgroud)
  1. 将以下内容添加到标签内文件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);
    }
Run Code Online (Sandbox Code Playgroud)
  1. 最后执行npm installnpm run dev命令。TODOS在 Web 浏览器中加载该站点,每当您将鼠标悬停在导航栏上的链接上时,就会看到客户端正在查询的服务器端路由。在控制台的网络选项卡中,请注意由于 Apollo实例是单例test,每秒和后续请求的路由响应速度快了多少。client