How to Configure React Relay with Vite

tutorial
Back

This is a short tutorial on how to properly configure React Relay with Vite. I've also written a small sample repo in case you prefer looking at code.

Step:1 Installing the dependencies

Install the dev dependencies first.

yarn add --dev \
    @types/react-relay@^14.1.2 \
    @types/relay-runtime@^14.1.3 \
    babel-plugin-relay@^14.1.0 \
    relay-compiler@^14.1.0 \
    vite-plugin-relay@^2.0.0 \
    graphql@^15.3.0

Then the prod dependencies.

yarn add react-relay@^14.1.0 relay-runtime@^14.1.0

Step 2: Configuring Relay

Create a file relay.config.json at the root of your repository with the following content.

{
  "src": "./src",
  "language": "typescript",
  // Change this to the location of your graphql schema
  "schema": "./src/graphql/schema.graphql",
  "exclude": [
    "**/node_modules/**",
    "**/__mocks__/**",
    "**/__generated__/**"
  ],
  "eagerEsModules": true
}

Step 3: Configuring the RelayEnvironment

Configure a global Environment as follows. This is how you tell Relay how to connect to your GraphQL endpoint. In this example I'm connecting to the Github API.

import {
  Environment,
  Network,
  RecordSource,
  Store,
  FetchFunction,
} from "relay-runtime";

const fetchRelay: FetchFunction =
  async (params, variables) => {
    const response = await fetch(
      "https://api.github.com/graphql",
      {
        method: "POST",
        headers: {
          "content-type":
            "application/json",
          authorization: `bearer ${process.env.GITHUB_TOKEN}`,
        },
        body: JSON.stringify({
          query: params.text,
          variables,
        }),
      }
    );

    // Get the response as JSON
    return await response.json();
  };

// Export a singleton instance of Relay Environment configured with our network function:
export const RelayEnvironment =
  new Environment({
    network: Network.create(fetchRelay),
    store: new Store(
      new RecordSource()
    ),
  });

Step 4: Setup the RelayEnvironment at the top of your React tree

import { RelayEnvironmentProvider } from "react-relay";
import { RelayEnvironment } from "./graphql/RelayEnvironment";

function App() {
  <RelayEnvironmentProvider
    environment={RelayEnvironment}
  >
    <TheRestOfYourApp />
  </RelayEnvironmentProvider>;
}

Step 5: Run the relay compiler

yarn relay --watch

Step 6: write your first component

In this example I'm fetching the name and number of stars from the Relay repository.

import {
  graphql,
  useLazyLoadQuery,
} from "react-relay";
// This will be auto-generated by the relay compiler once you've written the RepositoryQuery below.
import { RepositoriesQuery } from "./__generated__/RepositoriesQuery.graphql";

export function Repositories() {
  const { repository } =
    useLazyLoadQuery<RepositoriesQuery>(
      graphql`
        query RepositoriesQuery {
          repository(
            owner: "facebook"
            name: "relay"
          ) {
            name
            stargazerCount
          }
        }
      `,
      {}
    );

  if (!repository) {
    return null;
  }

  return (
    <div>
      <h1>Repositories</h1>
      <p>
        {repository.name} -{" "}
        {repository.stargazerCount}
      </p>
    </div>
  );
}

Step 7: Have fun!

Congrats, you've configured React Relay! I've also written a small repository where everything is already configured, you can find it here.

If you liked this article, follow me on twitter. I write about once a month about software engineering practices and programming in general.


Other posts you may like...

© Fernando Hurtado Cardenas.RSS