vite-plugin-graphql-loader

raw JSON →
5.0.1 verified Mon Apr 27 auth: no javascript

A Vite plugin for loading GraphQL .gql and .graphql files, based on the webpack graphql-tag/loader. Current version 5.0.1 requires graphql ^16.0.0 and supports Vite 5, 6, 7, and 8 as peer dependencies. Ships TypeScript types, provides default and named imports of DocumentNode objects, and handles fragment deduplication and source maps. Unlike vite-plugin-graphql-codegen, it does not generate TypeScript definitions from queries.

error Top-level await is not available in the configured target environment
cause Using a version before 3.0.1 with older bundlers or targets that don't support top-level await.
fix
Upgrade to v3.0.1 or later, or set a modern output target.
error Module not found: Error: Can't resolve 'graphql'
cause graphql is not installed (required as peer dependency since v5.0.0).
fix
Run npm install graphql or yarn add graphql.
error ERR_REQUIRE_ESM: require() of ES Module from ... not supported
cause Using CommonJS require() with v3.0.0+ which is ESM-only.
fix
Switch to import syntax or downgrade to v2.0.x.
error The requested module 'vite-plugin-graphql-loader' does not provide an export named 'default'
cause CommonJS default import mismatch; attempted const { default: graphqlLoader } = require(...) incorrectly.
fix
Use import graphqlLoader from 'vite-plugin-graphql-loader' in an ESM context.
breaking graphql is now a peer dependency in v5.0.0. Must be installed separately.
fix Run npm install graphql or yarn add graphql.
breaking Switched from CommonJS to ESM only starting v3.0.0. CJS projects must stay on v2.x.
fix Use import syntax or update to a modern Node version with ESM support. If you need CommonJS, pin to version 2.0.0.
breaking Vite peer dependency added in v5.0.0. Plugin only tested with Vite 5, 6, 7, and 8.
fix Ensure vite is installed and version matches one of the supported ranges.
gotcha Default export of a .graphql file is the first operation, not necessarily the first query if a fragment is defined first.
fix Use named exports for specific operations or rely on _queries export for robust access.
gotcha Fragments imported via #import are deduplicated, but multiple definitions of the same fragment can cause unexpected behavior if not careful.
fix Ensure fragment names are unique across all imported files to avoid deduplication issues.
npm install vite-plugin-graphql-loader
yarn add vite-plugin-graphql-loader
pnpm add vite-plugin-graphql-loader

Shows how to install and configure the plugin, then import a GraphQL file and use it with Apollo Client.

// vite.config.ts
import { defineConfig } from 'vite';
import graphqlLoader from 'vite-plugin-graphql-loader';

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

// App.ts
import MyQuery from './query.graphql';
import { useQuery } from '@apollo/client';

function App() {
  const { loading, data } = useQuery(MyQuery);
  return <div>{JSON.stringify(data)}</div>;
}