How to configure Relay.JS in Vite?

Viewed 469

I'm trying to migrate my React project from CRA to Vite, this is my vite.config.js:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import envCompatible from 'vite-plugin-env-compatible'
import relay from "vite-plugin-relay"
import macrosPlugin from "vite-plugin-babel-macros"
import path from 'path';
import fs from 'fs/promises';

export default defineConfig({
  resolve: {
    alias: {
      '~': path.resolve(__dirname, 'src'),
      '@material-ui/core': path.resolve(__dirname, 'node_modules/@material-ui/core')
    }
  },
  esbuild: {
    loader: "tsx",
    include: /src\/.*\.[tj]sx?$/,
    exclude: [],
  },
  optimizeDeps: {
    esbuildOptions: {
      plugins: [
        {
          name: "load-js-files-as-jsx",
          setup(build) {
            build.onLoad({ filter: /src\/.*\.js$/ }, async (args) => ({
              loader: "tsx",
              contents: await fs.readFile(args.path, "utf8"),
            }));
          },
        },
      ],
    },
  },
  define: {
    global: {},
  },
  plugins: [
    envCompatible(),
    react(),
    relay,
    //macrosPlugin(),
  ],
})

My GraphQL query files are like this:

import graphql from 'babel-plugin-relay/macro'

const getQuery = () => graphql`
    query UserQuery($id: ID!) {
      user(id: $id) {
        id
        fullName
      }
    }
  `

export default getQuery

When I tried to run the project in dev mode (command $ vite), I got this error:

Preset /* your preset */ requires a filename to be set when babel is called directly error message

So I did some search and replaced vite-plugin-relay to vite-plugin-babel-macros like this:

// others import
import relay from "vite-plugin-relay"
import macrosPlugin from "vite-plugin-babel-macros"

export default defineConfig({
  // configs like bellow
  plugins: [
    envCompatible(),
    react(),
    //relay,
    macrosPlugin(),
  ],
})

So I started to get a new error:

ReferenceError: require is not defined error message

How can I configure Relay to work on Vite.JS?

2 Answers

Might be a bit late, but the issue has been fixed in Relay@13 and you can find some workarounds in this thread for older versions of Relay :

https://github.com/facebook/relay/issues/3354

You can also try adding the option eagerEsModules: true to your relay babel plugin configuration.

Unless you have some specific usecase that requires the use of babel-plugin-relay, your issue should be resolved if you change your imports from

import graphql from 'babel-plugin-relay/macro'

to

import { graphql } from "react-relay";

You should only need the relay vite plugin at that point, and can remove vite-plugin-babel-macros

Related