react-apollo-loader

A webpack loader to make those who use React Apollo and GraphQL Code Generator happier. You can do:

Usage no npm install needed!

<script type="module">
  import reactApolloLoader from 'https://cdn.skypack.dev/react-apollo-loader';
</script>

README

react-apollo-loader

A webpack loader to make those who use React Apollo and GraphQL Code Generator happier. You can do:

import { useMyQuery } from './myQuery.graphql';

export default function(props: {}) {
  // The data is typed⚡️
  const { data, loading } = useMyQuery();
  
  return loading ? <div>loading</div> : <div>{data!.myQuery.text}</div>;
}

The blog post

Restrictions

Make sure you

  • use Apollo Client
  • use TypeScript
  • have a valid GraphQL server
  • are willing to have typed GraphQL response
  • have all your GraphQL documents in .graphql files, not in .tsx
    • This's going to be the preparation for the setup

Examples

Setup

  1. Install react-apollo-loader
yarn add -D react-apollo-loader
  1. Add the line to your .gitignore

react-apollo-loader will generate .d.ts right next to your .graphql GraphQL document files.

# .gitignore
+*.graphql.d.ts
  1. Make sure your GraphQL schema is able to get by this syntax.
  • If you have an isolated GraphQL Server, you can specify the URL endpoint, like https://yoursite.com/graphql.
  • Another recommended way is to specify a glob like **/*.graphqls. .graphqls is the extension that graphql-toolkit recognizes as GraphQL schema files. Note you cannot use the same extension of GrahpQL documents, these are different.
    • In this case, you would also want to load .graphqls by graphql-tag/loader to build executable schema. Set it up in your webpack.config.
  1. Setup the GraphQL document scanner in your webpack.config.{js,ts}. Note:
    • Make sure you're including only GraphQL documents, not GraphQL schema
    • The generated .tsx content still needs to be transpiled to .js so let Babel do that.
 const config: webpack.Configuration = {
   module: {
     rules: [
+      {
+        test: /\.graphql$/,
+        use: [
+          {
+            loader: 'babel-loader',
+            options: { presets: ['@babel/preset-typescript'] },
+          },
+          {
+            loader: 'graphql-codegen-loader',
+            options: {
+              schema: path.join(__dirname, 'schema.graphql'),
+            }
+          },
+        ],
+      }

Options

The required property is schema, where you can specify:

  • URL https://yoursite.com/graphql
  • JSON introspectino schema schema.json
  • Schema file schema.graphqls or the glob **/*.graphqls

Some of the other options are available, but note still some of the options are overwritten by react-apollo-loader.

License

MIT

TODO