### Watch Dependencies and Start Monaco Example
Source: https://github.com/graphql/graphiql/blob/main/DEVELOPMENT.md
Run 'yarn build:watch' to monitor changes in 'monaco-graphql' and 'graphql-language-service', and in another terminal, run 'yarn start-monaco' to launch the Monaco editor example.
```sh
yarn build:watch
```
```sh
yarn start-monaco
```
--------------------------------
### GraphQL Configuration File Example (JSON)
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-server/README.md
Example of a .graphqlrc or graphql.config.json file specifying the schema URL.
```json
{
"schema": "https://localhost:8000"
}
```
--------------------------------
### GraphQL Configuration File Example (JavaScript)
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-server/README.md
Example of a graphql.config.js or .graphqlrc.js file exporting the schema configuration.
```javascript
module.exports = { schema: 'https://localhost:8000' };
```
--------------------------------
### Install @graphiql/toolkit
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-toolkit/docs/create-fetcher.md
Install the @graphiql/toolkit package using npm. This is the first step to using the createGraphiQLFetcher utility.
```bash
npm install @graphiql/toolkit
```
--------------------------------
### Start GraphQL Language Service Server
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-cli/README.md
Starts the graphql-lsp server with a specified schema path.
```sh
graphql-lsp server --schema=localhost:3000
```
--------------------------------
### Install graphql-language-service-cli with NPM
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-cli/README.md
Installs the graphql-language-service-cli package globally using npm.
```sh
npm install -g graphql-language-service-cli
```
--------------------------------
### Basic GraphQL Editor Setup
Source: https://github.com/graphql/graphiql/blob/main/packages/cm6-graphql/README.md
Initialize a CodeMirror 6 editor with the GraphQL extension and a basic setup. Ensure a theme is provided to CodeMirror 6 for styling.
```js
import { basicSetup, EditorView } from 'codemirror';
import { graphql } from 'cm6-graphql';
const view = new EditorView({
doc: `mutation mutationName {
setString(value: "newString")
}`,
extensions: [basicSetup, graphql(myGraphQLSchema)],
parent: document.body,
});
```
--------------------------------
### Install graphql-language-service-cli with Yarn
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-cli/README.md
Installs the graphql-language-service-cli package globally using yarn.
```sh
yarn global add graphql-language-service-cli
```
--------------------------------
### Install Monaco-GraphQL Package
Source: https://github.com/graphql/graphiql/blob/main/README.md
Install the monaco-graphql package to integrate GraphQL language support into the Monaco editor.
```bash
npm install monaco-graphql
```
--------------------------------
### Start Vite Development Server
Source: https://github.com/graphql/graphiql/blob/main/examples/graphiql-vite/README.md
Run this command to start the Vite development server for local development.
```bash
yarn dev
```
--------------------------------
### Install codemirror-graphql
Source: https://github.com/graphql/graphiql/blob/main/packages/codemirror-graphql/README.md
Install the package using npm. This command installs the necessary files for CodeMirror GraphQL mode.
```sh
npm install codemirror-graphql
```
--------------------------------
### Install graphql-language-service-server
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-server/README.md
Install the package using npm or yarn. Node.js version 18.18.0 or later is required.
```bash
npm install graphql-language-service-server
# or
yarn add graphql-language-service-server
```
--------------------------------
### Install Legacy WebSocket Client
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-toolkit/docs/create-fetcher.md
This command installs the `subscriptions-transport-ws` package, which is required when using the `legacyWsClient` option.
```bash
npm install subscriptions-transport-ws
```
--------------------------------
### GraphQL Config package.json Example
Source: https://github.com/graphql/graphiql/blob/main/packages/vscode-graphql/README.md
Example of configuring GraphQL schema and documents within a `package.json` file. This is an alternative to using a separate `.graphqlrc` file.
```json
"graphql": {
"schema": "https://localhost:3001/graphql",
"documents": "**/*.{graphql,js,ts,jsx,tsx}"
}
```
--------------------------------
### GraphQL Server Directory Structure Example
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-server/README.md
Illustrates the recommended directory structure for managing multiple GraphQL projects, each with its own configuration and schema.
```text
./application
./productA
.graphqlrc.yml
ProductAQuery.graphql
ProductASchema.graphql
./productB
.graphqlrc.yml
ProductBQuery.graphql
ProductBSchema.graphql
```
--------------------------------
### Install cm6-graphql
Source: https://github.com/graphql/graphiql/blob/main/packages/cm6-graphql/README.md
Install the cm6-graphql package using npm.
```sh
npm install cm6-graphql
```
--------------------------------
### GraphQL Config YAML Example
Source: https://github.com/graphql/graphiql/blob/main/packages/vscode-graphql/README.md
Example of a minimal `.graphqlrc.yml` or `graphql.config.yml` file. Specifies the schema location and the paths to GraphQL documents.
```yaml
schema: 'schema.graphql'
documents: 'src/**/*.{graphql,js,ts,jsx,tsx}'
```
--------------------------------
### Install GraphiQL Code Exporter Plugin
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-plugin-code-exporter/README.md
Install the plugin using npm. Ensure you also install the required peer dependencies.
```sh
npm install @graphiql/plugin-code-exporter
```
```sh
npm install react react-dom graphql
```
--------------------------------
### Run Development Server
Source: https://github.com/graphql/graphiql/blob/main/examples/graphiql-nextjs/README.md
Commands to start the Next.js development server using different package managers.
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
--------------------------------
### Install GraphiQL Explorer Plugin
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-plugin-explorer/README.md
Install the GraphiQL Explorer plugin using npm. Ensure you also install the required peer dependencies: react, react-dom, and graphql.
```sh
npm install @graphiql/plugin-explorer
```
```sh
npm install react react-dom graphql
```
--------------------------------
### Install graphql-ws for Subscriptions
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-toolkit/docs/create-fetcher.md
Install graphql-ws as a peer dependency if you plan to use websocket subscriptions with GraphiQL.
```bash
npm install graphql-ws
```
--------------------------------
### Install GraphiQL Package
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql/README.md
Install the graphiql package along with its peer dependencies using npm.
```sh
npm install graphiql react react-dom graphql
```
--------------------------------
### Install Dependencies
Source: https://github.com/graphql/graphiql/blob/main/DEVELOPMENT.md
Install all project dependencies using Yarn. This command must be used instead of npm.
```sh
yarn
```
--------------------------------
### Custom wsClient Example using graphql-ws
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-toolkit/docs/create-fetcher.md
Demonstrates how to provide a pre-configured graphql-ws client instance to the wsClient option for advanced customization of the subscription transport.
```jsx
import * as React from 'react';
import { createRoot } from 'react-dom/client';
import { GraphiQL } from 'graphiql';
import { createClient } from 'graphql-ws';
import { createGraphiQLFetcher } from '@graphiql/toolkit';
const url = 'https://my-schema.com/graphql';
const subscriptionUrl = 'wss://my-schema.com/graphql';
const fetcher = createGraphiQLFetcher({
url,
wsClient: createClient({
url: subscriptionUrl,
keepAlive: 2000,
}),
});
export const App = () => ;
const root = createRoot(document.getElementById('graphiql'));
root.render();
```
--------------------------------
### GraphiQL Setup with React 19 and Explorer Plugin
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-plugin-explorer/example/index.html
This code snippet demonstrates the complete setup for GraphiQL 5 using React 19 and the GraphiQL Explorer plugin. It includes all necessary imports, fetcher configuration for a sample API, and the definition of plugins to be used with GraphiQL.
```javascript
import React from 'react';
import ReactDOM from 'react-dom/client';
import { GraphiQL, HISTORY_PLUGIN } from 'graphiql';
import { createGraphiQLFetcher } from '@graphiql/toolkit';
import { explorerPlugin } from '@graphiql/plugin-explorer';
import 'graphiql/setup-workers/esm.sh';
const fetcher = createGraphiQLFetcher({
url: 'https://countries.trevorblades.com',
});
const plugins = [
HISTORY_PLUGIN,
explorerPlugin(),
];
function App() {
return React.createElement(GraphiQL, {
fetcher,
plugins,
defaultEditorToolsVisibility: true,
});
}
const container = document.getElementById('graphiql');
const root = ReactDOM.createRoot(container);
root.render(React.createElement(App));
```
--------------------------------
### GraphQL Config TypeScript Example
Source: https://github.com/graphql/graphiql/blob/main/packages/vscode-graphql/README.md
Example of a `.graphqlrc.ts` or `graphql.config.ts` file. This configuration method allows for dynamic schema and document path definitions using TypeScript.
```typescript
export default {
schema: 'schema.graphql',
documents: '**/*.{graphql,js,ts,jsx,tsx}',
};
```
--------------------------------
### Custom Server Start with GraphQL Config
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-server/README.md
Starts the GraphQL language service server with custom configuration loaded via `graphql-config`. Supports specifying schema, root directory, and config file path.
```typescript
import { loadConfig } from 'graphql-config'; // 3.0.0 or later!
// with required params
const config = await loadConfig();
await startServer({
method: 'node',
// or instead of configName, an exact path (relative from rootDir or absolute)
// deprecated for: loadConfigOptions.rootDir. root directory for graphql config file(s), or for relative resolution for exact `filePath`.
// configDir: '',
loadConfigOptions: {
// any of the options for graphql-config@3 `loadConfig()`
schema: await config.getSchema(),
// rootDir is same as `configDir` before, the path where the graphql config file would be found by cosmic-config
rootDir: 'config/',
// or - the relative or absolute path to your file
filePath: 'exact/path/to/config.js', // (also supports yml, json, ts, toml)
// myPlatform.config.js/json/yaml works now!
configName: 'myPlatform',
},
});
```
--------------------------------
### Launch Monaco Editor Development Server
Source: https://github.com/graphql/graphiql/blob/main/DEVELOPMENT.md
Launch the webpack development server for the Monaco editor example. This is the fastest way to test changes related to the graphql-language-service, parser, etc.
```sh
yarn start-monaco
```
--------------------------------
### GraphiQL Setup with Code Exporter Plugin
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-plugin-code-exporter/example/index.html
This snippet shows the full setup for GraphiQL, including React, ReactDOM, GraphiQL itself, the toolkit for fetcher, and the code exporter plugin. It also configures Monaco Editor workers for JSON and GraphQL.
```javascript
{ "imports": { "react": "https://esm.sh/react@19.1.0", "react/jsx-runtime": "https://esm.sh/react@19.1.0/jsx-runtime", "react-dom": "https://esm.sh/react-dom@19.1.0", "react-dom/client": "https://esm.sh/react-dom@19.1.0/client", "graphiql": "https://esm.sh/graphiql@5?standalone&external=react,react-dom,@graphiql/react,graphql", "@graphiql/plugin-code-exporter": "https://esm.sh/@graphiql/plugin-code-exporter@5?standalone&external=react,@graphiql/react,graphql&deps=codemirror@5.65.3", "@graphiql/react": "https://esm.sh/@graphiql/react@0.37?standalone&external=react,react-dom,graphql", "@graphiql/toolkit": "https://esm.sh/@graphiql/toolkit@0.11?standalone&external=graphql", "graphql": "https://esm.sh/graphql@16.11.0", "regenerator-runtime/runtime": "https://esm.sh/regenerator-runtime@0.14/runtime" } } // Import React and ReactDOM import React from 'react'; import ReactDOM from 'react-dom/client'; // Import GraphiQL and the Explorer plugin import { GraphiQL, HISTORY_PLUGIN } from 'graphiql'; import { createGraphiQLFetcher } from '@graphiql/toolkit'; // Required to be before `@graphiql/plugin-code-exporter` import 'regenerator-runtime/runtime'; import { codeExporterPlugin } from '@graphiql/plugin-code-exporter'; import createJSONWorker from 'https://esm.sh/monaco-editor@0.52/esm/vs/language/json/json.worker.js?worker'; import createGraphQLWorker from 'https://esm.sh/monaco-graphql@1.7/esm/graphql.worker.js?worker'; import createEditorWorker from 'https://esm.sh/monaco-editor@0.52/esm/vs/editor/editor.worker.js?worker'; globalThis.MonacoEnvironment = { getWorker(_workerId, label) { console.info('MonacoEnvironment.getWorker', { label }); switch (label) { case 'json': return createJSONWorker(); case 'graphql': return createGraphQLWorker(); } return createEditorWorker(); }, }; const fetcher = createGraphiQLFetcher({ url: 'https://countries.trevorblades.com', }); function getQuery(arg, spaceCount = 2) { const spaces = ' '.repeat(spaceCount); const { query } = arg.operationDataList[0]; return spaces + query.replaceAll('\n', '\n' + spaces); } const codeExporter = codeExporterPlugin({ /** * Example code for snippets. See https://github.com/OneGraph/graphiql-code-exporter#snippets for details. */ snippets: [ { name: 'Example One', language: 'JavaScript', codeMirrorMode: 'jsx', options: [], generate: arg => ['export const query = graphql\`', getQuery(arg), '\`'].join('\n'), }, { name: 'Example Two', language: 'JavaScript', codeMirrorMode: 'jsx', options: [], generate: arg => [ 'import { graphql } from 'graphql'', '', 'export const query = graphql\`', getQuery(arg), '\`', ].join('\n'), }, ], }); const plugins = [HISTORY_PLUGIN, codeExporter]; function App() { return React.createElement(GraphiQL, { fetcher, plugins, defaultEditorToolsVisibility: true, }); } const container = document.getElementById('graphiql'); const root = ReactDOM.createRoot(container); root.render(React.createElement(App));
```
--------------------------------
### GraphiQL 1.x Class Component Example
Source: https://github.com/graphql/graphiql/blob/main/docs/migration/graphiql-2.0.0.md
Example of using GraphiQL as a class component in version 1.x, demonstrating ref attachment to access editor methods.
```tsx
import { createGraphiQLFetcher } from '@graphiql/toolkit';
import { GraphiQL } from 'graphiql';
import { Component } from 'react';
const fetcher = createGraphiQLFetcher({ url: 'https://my.endpoint' });
class MyComponent extends Component {
_graphiql: GraphiQL;
componentDidMount() {
const query = this._graphiql.getQueryEditor().getValue();
}
render() {
return (this._graphiql = r)} fetcher={fetcher} />;
}
}
```
--------------------------------
### Reproducing GraphiQL XSS Exploit Example
Source: https://github.com/graphql/graphiql/blob/main/docs/security/2021-introspection-schema-xss.md
This example demonstrates the phishing attack surface by accepting a `url` parameter. To reproduce, append `?url=https://graphql-xss-schema.netlify.app/graphql` to the in-codesandbox browser URL.
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import GraphiQL from 'graphiql';
import 'graphiql/graphiql.css';
function App() {
const fetcher = GraphiQL.createFetcher({
url: 'https://graphql-xss-schema.netlify.app/graphql',
});
return (
);
}
ReactDOM.render(, document.getElementById('root'));
```
--------------------------------
### Fetcher with WebSocket Connection Parameters
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-toolkit/docs/create-fetcher.md
Example demonstrating how to pass custom connection parameters, such as authorization tokens, for WebSocket connections using the wsConnectionParams option.
```jsx
const fetcher = createGraphiQLFetcher({
url: 'https://localhost:3000',
subscriptionUrl: 'https://localhost:3001',
wsConnectionParams: { Authorization: 'token 1234' },
});
const App = () => {
return ;
};
```
--------------------------------
### Import Monaco worker setup for Webpack/Turbopack
Source: https://github.com/graphql/graphiql/blob/main/docs/migration/graphiql-5.0.0.md
For Webpack or Turbopack projects like Next.js, import the GraphiQL worker setup module. This ensures Monaco workers are correctly configured.
```javascript
import 'graphiql/setup-workers/webpack';
```
--------------------------------
### GraphiQL 2.0 Function Component Example
Source: https://github.com/graphql/graphiql/blob/main/docs/migration/graphiql-2.0.0.md
Refactored example for GraphiQL 2.0 using function components. It demonstrates using GraphiQLProvider and GraphiQLInterface with context hooks to access editor state.
```jsx
import { useEditorContext } from '@graphiql/react';
import { createGraphiQLFetcher } from '@graphiql/toolkit';
import { GraphiQLInterface, GraphiQLProvider } from 'graphiql';
import { useEffect } from 'react';
const fetcher = createGraphiQLFetcher({ url: 'https://my.endpoint' });
function MyComponent() {
return (
);
}
function InsideContext() {
// Calling this hook would not work in `MyComponent` (it would return `null`)
const { queryEditor } = useEditorContext();
useEffect(() => {
const query = queryEditor.getValue();
}, [queryEditor]);
return ;
}
```
--------------------------------
### Basic GraphQL Mode Setup
Source: https://github.com/graphql/graphiql/blob/main/packages/codemirror-graphql/README.md
Configure CodeMirror to use the GraphQL mode, enabling linting and autocompletion with a provided schema. Ensure all necessary CodeMirror addons and the codemirror-graphql modules are imported.
```ts
import type { ValidationContext, SDLValidationContext } from 'graphql';
import CodeMirror from 'codemirror';
import 'codemirror/addon/hint/show-hint';
import 'codemirror/addon/lint/lint';
import 'codemirror-graphql/hint';
import 'codemirror-graphql/lint';
import 'codemirror-graphql/mode';
CodeMirror.fromTextArea(myTextarea, {
mode: 'graphql',
lint: {
schema: myGraphQLSchema,
validationRules: [ExampleRule],
},
hintOptions: {
schema: myGraphQLSchema,
},
});
```
--------------------------------
### GraphQL String Type Example
Source: https://github.com/graphql/graphiql/blob/main/packages/cm6-graphql/__tests__/types.txt
Shows a GraphQL query using a string literal and its AST representation.
```graphql
{ test(v1: "abc") }
```
```plaintext
Document(OperationDefinition(SelectionSet("{ ",Selection(Field(FieldName,Arguments("(",Argument(ArgumentAttributeName,StringValue), ") ")))," } ")))
```
--------------------------------
### Initialize Monaco GraphQL Mode
Source: https://github.com/graphql/graphiql/blob/main/packages/monaco-graphql/README.md
Initialize the monaco-graphql mode with schema configurations and set up the worker. This example demonstrates how to configure schemas and integrate the GraphQL worker for language features.
```ts
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import { initializeMode } from 'monaco-graphql/initializeMode'; // `monaco-graphql/esm/initializeMode` is deprecated but still works
// you can also configure these using the webpack or vite plugins for `monaco-editor`
import GraphQLWorker from 'worker-loader!monaco-graphql/esm/graphql.worker';
// instantiates the worker & language features with the schema!
const MonacoGraphQLAPI = initializeMode({
schemas: [
{
schema: myGraphqlSchema as GraphQLSchema,
// anything that monaco.URI.from() is compatible with
uri: 'https://my-schema.com',
uri: '/my-schema.graphql',
// match the monaco file uris for this schema.
// accepts specific uris and anything `picomatch` supports.
// (everything except bracket regular expressions)
fileMatch: ['**/*.graphql'],
// note: not sure if ^ works if the graphql model is using urls for uris?
},
],
});
globalThis.MonacoEnvironment = {
getWorker(_workerId: string, label: string) {
if (label === 'graphql') {
return new GraphQLWorker();
}
// if you are using vite or webpack plugin, it will be found here
return new Worker('editor.worker.js');
},
};
monaco.editor.create(document.getElementById('someElementId'), {
value: 'query { }',
language: 'graphql',
formatOnPaste: true,
});
```
--------------------------------
### GraphQL Number Type Examples
Source: https://github.com/graphql/graphiql/blob/main/packages/cm6-graphql/__tests__/types.txt
Demonstrates GraphQL queries with integer, float, and negative/scientific notation numbers, along with their AST representations.
```graphql
{ test(v1: 123) }
```
```graphql
{ test(v1: 123.01) }
```
```graphql
{ test(v1: -1.35384e+3) }
```
```plaintext
Document(
OperationDefinition(SelectionSet("{ ",Selection(Field(FieldName,Arguments("(",Argument(ArgumentAttributeName,IntValue), ") ")))," } "))),
OperationDefinition(SelectionSet("{ ",Selection(Field(FieldName,Arguments("(",Argument(ArgumentAttributeName,FloatValue), ") ")))," } "))),
OperationDefinition(SelectionSet("{ ",Selection(Field(FieldName,Arguments("(",Argument(ArgumentAttributeName,FloatValue), ") ")))," } "))
)
```
--------------------------------
### Configure Coc.nvim for GraphQL Language Server
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-cli/README.md
Example configuration for Coc.nvim to use the graphql-lsp server. This allows for legacy graphql-config file formats.
```json
{
"languageserver": {
"graphql": {
"command": "graphql-lsp",
"args": ["server", "-m", "stream"],
// customize filetypes to your needs
"filetypes": ["typescript", "typescriptreact", "graphql"],
"settings": {
"graphql-config.load.legacy": true
}
}
}
}
```
--------------------------------
### GraphQL List Type Examples
Source: https://github.com/graphql/graphiql/blob/main/packages/cm6-graphql/__tests__/types.txt
Shows GraphQL queries with empty lists, lists of strings, and mixed-type lists, including their AST representations.
```graphql
{ test(v1: []) }
```
```graphql
{ test(v1: ["abc", "def"]) }
```
```graphql
{ test(v1: ["abc", ABC, 123, 213.01, true, null]) }
```
```plaintext
Document(
OperationDefinition(SelectionSet("{ ",Selection(Field(FieldName,Arguments("(",Argument(ArgumentAttributeName,ListValue("[", "]")), ") ")))," } "))),
OperationDefinition(SelectionSet("{ ",Selection(Field(FieldName,Arguments("(",Argument(ArgumentAttributeName,ListValue("[",StringValue,StringValue,"]")), ") ")))," } "))),
OperationDefinition(SelectionSet("{ ",Selection(Field(FieldName,Arguments("(",Argument(ArgumentAttributeName,ListValue("[",StringValue,EnumValue,IntValue,FloatValue,BooleanValue,NullValue,"]")), ") ")))," } "))
)
```
--------------------------------
### Create Fetcher with Isomorphic Fetch for SSR
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-toolkit/docs/create-fetcher.md
This example shows how to create a fetcher using `isomorphic-fetch` for Server-Side Rendering (SSR) scenarios. This ensures fetch requests are handled consistently across environments.
```jsx
import * as React from 'react';
import { createRoot } from 'react-dom/client';
import { GraphiQL } from 'graphiql';
import { fetch } from 'isomorphic-fetch';
import { createGraphiQLFetcher } from '@graphiql/toolkit';
const url = 'https://my-schema.com/graphql';
const fetcher = createGraphiQLFetcher({ url, fetch });
export const App = () => ;
const root = createRoot(document.getElementById('graphiql'));
root.render();
```
--------------------------------
### GraphiQL CDN Usage (ESM-based)
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql/README.md
Demonstrates how to use GraphiQL via an ESM-based CDN. This approach leverages modern JavaScript modules for setup.
```html
GraphiQL Example
Loading...
```
--------------------------------
### GraphiQL Setup with React and Explorer Plugin
Source: https://github.com/graphql/graphiql/blob/main/examples/graphiql-cdn/index.html
This snippet initializes GraphiQL with a fetcher pointing to a GraphQL endpoint and includes the history and explorer plugins. It's designed for direct use in an HTML file leveraging CDN-hosted ES Modules.
```html
GraphiQL 5 CDN Example
Loading…
```
```javascript
const imports = {
react: "https://esm.sh/react@19.2.5",
"react/": "https://esm.sh/react@19.2.5/",
"react-dom": "https://esm.sh/react-dom@19.2.5",
"react-dom/": "https://esm.sh/react-dom@19.2.5/",
graphiql: "https://esm.sh/graphiql@5.2.2?standalone&external=react,react-dom,@graphiql/react,graphql",
"graphiql/": "https://esm.sh/graphiql@5.2.2/",
"@graphiql/plugin-explorer": "https://esm.sh/@graphiql/plugin-explorer@5.1.1?standalone&external=react,@graphiql/react,graphql",
"@graphiql/react": "https://esm.sh/@graphiql/react@0.37.3?standalone&external=react,react-dom,graphql,@graphiql/toolkit,@emotion/is-prop-valid",
"@graphiql/toolkit": "https://esm.sh/@graphiql/toolkit@0.11.3?standalone&external=graphql",
graphql: "https://esm.sh/graphql@16.13.2",
"@emotion/is-prop-valid": "data:text/javascript,"
};
const integrity = {
"https://esm.sh/react@19.2.5": "sha384-ZNmUQ9QQgyl95nnD/FJTBQn2ZEPTbWtMuWCXTKWNuF6Si7nC+6bvSgk5LWu+ELHn",
"https://esm.sh/react-dom@19.2.5": "sha384-qtNxBzn9gBs3CmJItMuvIVyjW3VIU0/rzGhCm9MippVU1BpR/c4VgaFYDIg/FrY2",
"https://esm.sh/graphiql@5.2.2": "sha384-MBVZMq1pmz8DwpwIWPWLk2tmS6tGiSi6WwbXvy9NhuDYASAAWd2m96xbxLqszig9",
"https://esm.sh/graphiql@5.2.2?standalone&external=react,react-dom,@graphiql/react,graphql": "sha384-SzHBEbcQfhvmwqh5Vtat9k7b/kIzmdVO3KMzQiAYwcxCA9x7vZwFRUgjzN1AeV3q",
"https://esm.sh/@graphiql/plugin-explorer@5.1.1": "sha384-83REbLb9KtIhL/6J1n91SLoP0648KOKZLIDdHRx/a0E7T3ajq6PzKz+815SCfN52",
"https://esm.sh/@graphiql/react@0.37.3?standalone&external=react,react-dom,graphql,@graphiql/toolkit,@emotion/is-prop-valid": "sha384-iZsbTy9B0VcX2BOTdqMuX0uJ9Hff5GbG2QeOt4OeMp0GHza76dwQaYQYNYkZkIVq",
"https://esm.sh/@graphiql/toolkit@0.11.3?standalone&external=graphql": "sha384-ZsnupyYmzpNjF1Z/81zwi4nV352n4P7vm0JOFKiYnAwVGOf9twnEMnnxmxabMBXe",
"https://esm.sh/graphql@16.13.2": "sha384-TQg9alwG3P9fzBErDW011vKuyTnrwpBZsl3SdMAh6DwBcv9ezFOl0djGI/68VOyy"
};
import React from 'react';
import ReactDOM from 'react-dom/client';
import { GraphiQL, HISTORY_PLUGIN } from 'graphiql';
import { createGraphiQLFetcher } from '@graphiql/toolkit';
import { explorerPlugin } from '@graphiql/plugin-explorer';
import 'graphiql/setup-workers/esm.sh';
const fetcher = createGraphiQLFetcher({
url: 'https://countries.trevorblades.com',
});
const plugins = [
HISTORY_PLUGIN,
explorerPlugin()
];
function App() {
return React.createElement(GraphiQL, {
fetcher,
plugins,
defaultEditorToolsVisibility: true,
});
}
const container = document.getElementById('graphiql');
const root = ReactDOM.createRoot(container);
root.render(React.createElement(App));
```
--------------------------------
### GraphQL CLI Options Help
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-cli/README.md
Displays the help information for the graphql-lsp command-line interface, detailing available commands and options.
```sh
Usage: graphql-lsp
[-h | --help][-c | --configDir] {configDir}
[-t | --text] {textBuffer}
[-f | --file] {filePath}
[-s | --schema] {schemaPath}
Options:
-h, --help Show help [boolean]
-t, --text Text buffer to perform GraphQL diagnostics on.
Will defer to --file option if omitted.
Overrides the --file option, if any.
[string]
-f, --file File path to perform GraphQL diagnostics on.
Will be ignored if --text option is supplied.
[string]
--row A row number from the cursor location for GraphQL
autocomplete suggestions.
If omitted, the last row number will be used.
[number]
--column A column number from the cursor location for GraphQL
autocomplete suggestions.
If omitted, the last column number will be used.
[number]
-c, --configDir Path to the .graphqlrc.yml configuration file.
Walks up the directory tree from the provided config
directory, or the current working directory, until a
.graphqlrc is found or the root directory is found.
[string]
-s, --schemaPath a path to schema DSL file
[string]
At least one command is required.
Commands: "server, validate, autocomplete, outline"
```
--------------------------------
### Install vite-plugin-monaco-editor for Vite
Source: https://github.com/graphql/graphiql/blob/main/docs/migration/graphiql-5.0.0.md
Install the necessary Vite plugin for Monaco editor integration. This is a prerequisite for configuring Monaco workers in Vite projects.
```sh
npm install vite-plugin-monaco-editor --save-dev
```
--------------------------------
### Initialize GraphQL Language Server
Source: https://github.com/graphql/graphiql/blob/main/packages/graphql-language-service-server/README.md
Initialize the server using the startServer function. This is typically used when developing IDE extensions.
```typescript
import { startServer } from 'graphql-language-service-server';
await startServer({
method: 'node',
});
```
--------------------------------
### Run GraphiQL Development Server
Source: https://github.com/graphql/graphiql/blob/main/DEVELOPMENT.md
Launch the Vite development server specifically for GraphiQL. This is the recommended command for focused GraphiQL development.
```sh
yarn dev:graphiql
```
--------------------------------
### Initialize GraphiQLProvider with Fetcher
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql-react/README.md
Set up the GraphiQLProvider with a fetcher function to handle GraphQL requests. The fetcher can be created using createGraphiQLFetcher from @graphiql/toolkit.
```jsx
import { GraphiQLProvider } from '@graphiql/react';
import { createGraphiQLFetcher } from '@graphiql/toolkit';
const fetcher = createGraphiQLFetcher({
url: 'https://my.graphql.api/graphql',
});
function MyGraphQLIDE() {
return (
Hello GraphQL
);
}
```
--------------------------------
### Setup Workers for GraphiQL UMD Bundle
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql/index.html
Configures the Monaco editor environment to use web workers for different language types within the GraphiQL UMD bundle. This setup is crucial for the editor's functionality when bundled for CDN usage.
```javascript
function getWorkerUrl(label) {
switch (label) {
case 'json':
return '/dist/workers/json.worker.js';
case 'graphql':
return '/dist/workers/graphql.worker.js';
}
return '/dist/workers/editor.worker.js';
}
globalThis.MonacoEnvironment = {
// `MonacoEnvironment.getWorkerUrl` throws Uncaught SyntaxError: Unexpected token 'export',
// we use `MonacoEnvironment.getWorker` instead
getWorker(_workerId, label) {
console.log('setup workers in cdn');
const url = new URL(getWorkerUrl(label), import.meta.url);
return new Worker(url, { type: 'module' });
},
};
```
--------------------------------
### GraphQL Enum Type Example
Source: https://github.com/graphql/graphiql/blob/main/packages/cm6-graphql/__tests__/types.txt
Illustrates a GraphQL query using an enum value and its AST representation.
```graphql
{ test(v1: ABC) }
```
```plaintext
Document(OperationDefinition(SelectionSet("{ ",Selection(Field(FieldName,Arguments("(",Argument(ArgumentAttributeName,EnumValue), ") ")))," } ")))
```
--------------------------------
### Render GraphiQL Component
Source: https://github.com/graphql/graphiql/blob/main/packages/graphiql/README.md
Basic setup to render the GraphiQL component in a React application using createGraphiQLFetcher.
```jsx
import { createGraphiQLFetcher } from '@graphiql/toolkit';
import { GraphiQL } from 'graphiql';
import { createRoot } from 'react-dom/client';
import 'graphiql/style.css';
const fetcher = createGraphiQLFetcher({ url: 'https://my.backend/graphql' });
const root = createRoot(document.getElementById('root'));
root.render();
```
--------------------------------
### GraphQL Config: Schema as URL
Source: https://github.com/graphql/graphiql/blob/main/packages/vscode-graphql-execution/README.md
Configure your GraphQL schema by providing a URL. This is a basic setup for the extension.
```yaml
schema: https://localhost:3000/graphql
```
--------------------------------
### Initialize MonacoGraphQLAPI Dynamically
Source: https://github.com/graphql/graphiql/blob/main/packages/monaco-graphql/README.md
Illustrates how to initialize the MonacoGraphQLAPI dynamically using `initializeMode` from 'monaco-graphql/initializeMode', similar to the full sync demo.
```typescript
import { initializeMode } from 'monaco-graphql/initializeMode';
const api = initializeMode(config);
```
--------------------------------
### Vue GraphQL Query
Source: https://github.com/graphql/graphiql/blob/main/packages/vscode-graphql-syntax/tests/__fixtures__/test-js.md
Provides an example of defining a GraphQL query within a Vue component's script section.
```vue