react-apollo-loader
v0.2.2
Published
A webpack loader to make those who use [React Apollo](https://github.com/apollographql/react-apollo#readme) and [GraphQL Code Generator](https://graphql-code-generator.com/) _happier_. You can do:
Downloads
9
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>;
}
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
- Install react-apollo-loader
yarn add -D react-apollo-loader
- 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
- 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
bygraphql-tag/loader
to build executable schema. Set it up in your webpack.config.
- In this case, you would also want to load
- 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
- [ ] Write test
- [ ] Write webpack loader option schema