0.2.2 • Published 6 years ago
react-apollo-loader v0.2.2
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
.graphqlfiles, 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..graphqlsis 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.graphqlsbygraphql-tag/loaderto build executable schema. Set it up in your webpack.config.
- 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
.tsxcontent still needs to be transpiled to.jsso 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.graphqlsor 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