Git Product home page Git Product logo

vite-plugin-relay's Introduction

Vite Plugin Relay

NPM CI workflow

Add relay support to your Vite projects.

❤️ Special thanks to:

I do not actively use this project anymore, however, it will still receive periodic updates.

Usage

Follow Relay's guide on how to add Relay to your project.

⚠️ Note: Install babel-plugin-relay (>= 13.0.1) as devDependencies as instructed, but skip its configuration. vite-plugin-relay will invoke the babel plugin for you!

Add vite-plugin-relay to your devDependencies:

yarn add vite-plugin-relay -D

Add vite-plugin-relay to your Vite configuration (vite.config.ts or vite.config.js):

import { defineConfig } from "vite";
import relay from "vite-plugin-relay";

export default defineConfig({
  plugins: [..., relay],
});

Configure relay-compiler to output artifacts with export default syntax, by setting eagerEsModules to true:

{
  "relay": {
    "src": "./src",
    "schema": "./src/schema.graphql",
    "language": "typescript",
    "eagerEsModules": true,
    "exclude": ["**/node_modules/**", "**/__mocks__/**", "**/__generated__/**"]
  }
}

Now your project is setup to use Relay with Vite!

How this plugin works

Under the hood we are invoking the official babel-plugin-relay. This ensures that our plugin and babel-plugin-relay do not get out of sync over time and also reduces the maintainance costs of this project.

Since v13 babel-plugin-relay automatically gets its configuration from either the package.json, relay.config.js or relay.config.json, so our plugin also doesn't have to expose a configuration API.

Common Issues

Uncaught ReferenceError: global is not defined

If you experience this error in your browser console when using the plugin add the following define to your index.html file before importing your Javascript:

<script>
  let global = globalThis;
</script>

Server Side Rendering

If you are planning to use this plugin with server side rendering you may need to define window. You could do this by putting the following snippet in your entry-server.js file.

if (typeof (window as any).global === 'undefined') {
  (window as any).global = globalThis;
}

Contributing

git clone ...
pnpm i
# If you have never run Playwright run `npx playwright install` to setup your system.
cd examples/vite-3
pnpm dev

pnpm format # Do this before doing a commit

vite-plugin-relay's People

Contributors

cliedeman avatar dependabot[bot] avatar kesne avatar koistya avatar oscartbeaumont avatar tmair avatar tobias-tengler avatar tony avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

vite-plugin-relay's Issues

How to use with Vitest Workspaces

Hello, how I can use this plugin with Vitest Workspaces?

One issue I'm facing is reading the relay configuration located in each workspace. Currently the plugin reads the configuration from the current directory and not from the workspace directory.

I want it to read the configuration in /packages/abc/relay.config.js instead of /relay.config.js when running the vitest command in the root directory.

One idea would be to allow you to submit Relay settings directly to this plugin via Javascript.

Is this supposed to make `relay-compiler` automatically run when `vite` is invoked?

currently I have:

  "scripts": {
    "dev": "pnpm relay && vite",
    "build": "pnpm relay && tsc && vite build",
    "preview": "vite preview",
    "relay": "relay-compiler"
  },

in my package.json.

I was hoping that I could just have something more like:

  "scripts": {
-    "dev": "pnpm relay && vite",
+    "dev": "vite",
-    "build": "pnpm relay && tsc && vite build",
+    "build": "tsc && vite build",
    "preview": "vite preview",
    "relay": "relay-compiler"
  },

by using this plugin, but maybe I am not understanding this plugin's usecase.

Allow user to opt out of define or remove it

  config: () => ({
    define: {
      global: "globalThis",
    },
  }),

breaks imports that have the word global in them. E.g: jss-plugin-global

Add a config option to the plugin to opt out of this behaviour or just remove it.

The docs have also been updated to recommend against placing global inside define

For anyone else encounrting this issue you can use this workaround

import type { Plugin } from "vite";

const viteRelayFix = {
  name: "vite:relay-fix",
  config: (cfg) => {
    delete cfg.define.global;
    return cfg;
  },
} as Plugin;

Thanks
Ciaran

Making it work without babel

I tried using your plugin to have Storybook with the Vite builder, but wasn't able to and had to resort to doing something similar.

I found this GitHub gist from @sciyoshi, which works well when using esbuild as the bundler, but as Vite uses esbuild + rollup, I had to modify it to make it a Rollup plugin.

Here's my code:

import crypto from 'crypto'; // node default crypto (no need to install)
import { parse } from 'graphql'; // can be a pure dependency or peer dependency

const relay = {
  name: 'vite:relay',
  config: () => ({
    define: {
      global: 'globalThis',
    },
  }),
  async transform(src, id) {
    let code = src;
    if (/.(t|j)sx?$/.test(id) && src.includes('graphql`')) {
      const imports = [];

      code = code.replace(/graphql`([\s\S]*?)`/gm, (_, query) => {
        const operationName = parse(query).definitions[0]?.name?.value;
        if (!operationName) throw new Error(`Incorrect GraphQL operation in ${id}`);

        let id = `graphql__${crypto.randomBytes(10).toString('hex')}`;
        imports.push(
          `import ${id} from "@cercle/common/relay/__generated__/${operationName}.graphql.ts";`
        );
        return id;
      });
      code = imports.join('\n') + code;
    }

    return {
      code,
      map: null,
    };
  },
};

This is also slightly faster as it doesn't have the overhead that babel transform has.

Issues with root + tsconfigPaths paths setup

Hi. I'm trying to use vite-plugin-relay on a project that uses src as the root, and uses tsconfig paths for absolute imports.

vitest.config.ts

import react from "@vitejs/plugin-react"
import tsconfigPaths from "vite-tsconfig-paths"
import { defineConfig } from "vitest/config"
import relay from "vite-plugin-relay"

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), tsconfigPaths(), relay],
  test: {
    globals: true,
    environment: "jsdom",
    setupFiles: ["./__tests__/setupVitestTests.ts"]
  },
  root: "src",
})

relay.config.js

module.exports = {
  src: "./src",
  schema: "./schema.graphql",
  schemaExtensions: ["./src"],
  exclude: [
    "**/__generated__/**",
    "**/__mocks__/**",
    "**/node_modules/**",
    "src/.next/**",
  ],
  language: "typescript",
  eagerEsModules: true,
  artifactDirectory: "./src/lib/graphql/__generated__",
}

tsconfig paths:

"paths": {
   "@/*": ["./*"]
}

Imports:

import { CollectionWatchlistButtonTestQuery } from "@/lib/graphql/__generated__/CollectionWatchlistButtonTestQuery.graphql"

When trying to run tests, vitest fails to find generated modules:

Screenshot 2023-05-31 at 08 16 40

ReferenceError: global is not defined

I was trying to get this plugin up and running in my own project but bumped into the following error ReferenceError: global is not defined. So then the exploration started: I've checked out this repo and tried to boot the example app and I got the same error.

It happens only when running the dev server, the production build goes just fine. Therefore, the end-to-end tests are not failing. I could "fix" it by changing the vite.config.ts content with:

import { defineConfig } from "vite";
import reactRefresh from "@vitejs/plugin-react-refresh";
import relay from "vite-plugin-relay";

export default defineConfig({
  define: {
    global: {
      global: 'globalThis'
    }
  },
  plugins: [reactRefresh(), relay],
});

but actually I have no idea why that works. I've noticed that something similar has been changed in #152 but I'm not too much into this to completely oversee the impact.

Full Stacktrace
RelayReferenceMarker.js:333 Uncaught ReferenceError: global is not defined
    at node_modules/relay-runtime/lib/store/RelayPublishQueue.js (RelayReferenceMarker.js:333)
    at __require2 (chunk-ENMAWK7U.js?v=1254bb04:36)
    at node_modules/relay-runtime/lib/store/RelayModernEnvironment.js (RelayModernStore.js:652)
    at __require2 (chunk-ENMAWK7U.js?v=1254bb04:36)
    at node_modules/relay-runtime/lib/index.js (index.js:10)
    at __require2 (chunk-ENMAWK7U.js?v=1254bb04:36)
    at node_modules/relay-runtime/index.js (index.js:10)
    at __require2 (chunk-ENMAWK7U.js?v=1254bb04:36)
    at node_modules/react-relay/lib/ReactRelayContext.js (ReactRelayContext.js:15)
    at __require2 (chunk-ENMAWK7U.js?v=1254bb04:36)

Upgrade babel-plugin-relay to v15

babel-plugin-relay v15 is available, but this library depends on v14.

ABC@workspace:. provides babel-plugin-relay@npm:15.0.0 with version 15.0.0, which doesn't satisfy the following requirements:
➤ YN0000: vite-plugin-relay@npm:2.0.0 [f5404] → ^14.1.0 ✘

Is it possible to upgrade this plugin to use v15? Is there another way to remove this warning from yarn?

Expose a config option for artifactDirectory

relay-compiler and babel-plugin-relay have an artifactDirectory config option to control the location of the generated files. The babel plugin and the relay-compiler config need to have the same location configure to work correctly. Currently this plugin doesn't expose a mechanism for configuring this so users cannot use this option in the relay compiler.

Basic Config Help

Hello. I followed the getting started instructions to get up and running with the plugin. Unfortunately, things aren't working as expected.

Here is my vite config:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import relay from 'vite-plugin-relay'
export default defineConfig({
  server: {
    port: 3000,
  },
  plugins: [react(), relay],
});

The order of the plugins does not seem to matter. And here's my graphql query:

import {graphql} from "relay-runtime";
const getUserQuery = graphql`
  query GetUserQuery($input: GetRequest!) {
    getUser(input: $input) {
      id
    }
  }
`
export default getUserQuery;

Unfortunately, this results in the following error

Uncaught Invariant Violation: graphql: Unexpected invocation at runtime. Either the Babel transform was not set up, or it failed to identify this call site. Make sure it is being used verbatim as `graphql`. Note also that there cannot be a space between graphql and the backtick that follows.
    at invariant (http://localhost:3000/node_modules/.vite/deps/chunk-HCDSWF2A.js?v=97bd1526:224:19)
    at graphql (http://localhost:3000/node_modules/.vite/deps/chunk-HCDSWF2A.js?v=97bd1526:1176:21)
    at http://localhost:3000/src/queries/LoginMutation.ts?t=1660257715549:2:30

Which leads me to believe that the plugin isn't running. How can I configure the plugin to run the babel transformation?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.