Rails React GraphQL Typescript Apollo 1 2 3 4 5
# Create a new rails project
$ rails new my_app -j esbuild -c tailwind
$ cd my_app
# Add Sorbet
$ bundle add sorbet-static-and-runtime
$ bundle add tapioca -g development --require false
$ bundle add spoom -g development # optional to manage incremental typing of individual files
# Add Graphql
$ bundle add graphql
$ rails g graphql:install
# Make some folders and files for our React application
$ mkdir app/javascript/components
$ touch app/javascript/components/application.tsx
# Add in our React and Apollo dependencies
$ yarn add react react-dom
$ yarn add @apollo/client graphql
# Graphql codegen
$ yarn add -D @graphql-codegen/cli
$ yarn graphql-codegen init
# or
$ yarn add graphql-typescript-definitions
# Front end testing
$ yarn add @shopify/react-testing
# we use `bin/dev` instead of `bin/rails s`
$ bin/dev
- Application built with: Choose "React"
- Schema: app/javascript/graphql/schema.graphql
- Operations and fragments: app/javascript/**/*.tsx
- Plugins: Leave default selected
- Output path: app/javascript/graphql/types.tsx
- Generate introspection file: Choose "no" because the graphql gem has done this already with the Rake task we just ran.
- Name config file: Leave it as the default, codegen.yml
- Script in package.json: gql:codegen
require "graphql/rake_task"
GraphQL::RakeTask.new(
schema_name: "BooksSchema",
directory: "./app/javascript/graphql",
dependencies: [:environment]
)
# generate a Graphql type
$ rails g graphql:object Book
# make the schema available to Apollo and Typescript
$ rake graphql:schema:dump && yarn gql:codegen
Footnotes
-
https://egghead.io/blog/rails-graphql-typescript-react-apollo ↩
-
https://blog.dennisokeeffe.com/blog/2022-02-19-rails-7-using-react-with-esbuild ↩
-
https://betterprogramming.pub/react-with-rails-2022-bd28e1fcd355 ↩
-
https://medium.com/rd-shipit/how-to-set-up-a-rails-7-project-with-react-and-jest-f2e016bfbdf3 ↩
-
https://www.strictmode.io/articles/setting-up-rails-7-for-typescript-and-react ↩