Relay Compiler
raw JSON →The Relay Compiler is the build-time tool for the Relay GraphQL client, currently at stable version 20.1.1. It transforms GraphQL fragments and queries defined in JavaScript/TypeScript files into optimized runtime artifacts, including persisted query mappings. Released under a regular cadence with major updates every few months, it provides strict schema validation, type-safe fragment composition, and support for directives like @alias, @catch, and @preloadable. Key differentiators include deep integration with React via Suspense and load-as-you-render patterns, zero-runtime overhead from compiled operations, and strong typing via generated Flow or TypeScript definitions. Unlike Apollo's codegen, Relay Compiler enforces a global schema and prevents over-fetching by design through its colocation model.
Common errors
error Error: Failed to compile. Schema not found at path ./schema.graphql ↓
error GraphQL: Validation error of type FragmentSpreadTargetType: argument 'alias' is required ↓
error TypeError: relay-compiler is not a function or module ↓
error Error: Cannot find module 'relay-compiler/package.json' ↓
Warnings
breaking Starting in v18, @alias is required on conditional fragments (fragments with @skip/@include or type conditions). ↓
breaking v20.1.0 removed the ability to set config_id in @live Relay directives. ↓
deprecated The customScalars config option was renamed to customScalarTypes in v16.2.0. ↓
breaking Relay Compiler is now ESM-only as of v18. CommonJS require() will fail. ↓
gotcha The @catch directive is experimental until v18; it may have breaking changes without major version bump. ↓
Install
npm install relay-compiler yarn add relay-compiler pnpm add relay-compiler Imports
- graphql wrong
const graphql = require('relay-compiler')correctimport { graphql } from 'relay-runtime' - RelayCompiler wrong
import { RelayCompiler } from 'relay-compiler'correctimport RelayCompiler from 'relay-compiler' - RelayCompilerOptions wrong
import { RelayCompilerOptions } from 'relay-compiler'correctimport type { RelayCompilerOptions } from 'relay-compiler'
Quickstart
// Install: npm install relay-compiler relay-runtime
// Generate schema.graphql first (e.g., from server introspection)
// Run the compiler
const { execSync } = require('child_process');
execSync('npx relay-compiler --src ./src --schema ./schema.graphql --language typescript', { stdio: 'inherit' });
// Use in code
import { graphql } from 'relay-runtime';
const query = graphql`
query MyQuery {
viewer {
name
}
}
`;
fetchGraphQL(query, {})
.then(data => console.log(data));
// GraphQL fragments must be tagged with graphql and the file must match the naming convention
// The compiler generates __generated__/MyQuery.graphql.ts