I would like to use create-react-app
without ejecting my Relay app.
According to Relay documentation I will need the babel-relay-plugin
. The relay-starter-kit
configures this in a .babelrc.
What would be the easiest way to accomplish this? Is there a way to enable relay
without ejecting?
CRA 2 supports Babel macros which makes things a whole lot easier. Essentially you have to add babel-plugin-relay
and use it with import graphql from 'babel-plugin-relay/macro'
. Check out the docs for more information.
One option is to create your own fork of react-scripts
that adds babel-relay-plugin
to .babelrc
. Creating a fork of react-scripts
is documented as method #3 in this Medium post. You can publish the fork as a scoped package to npm and then use that when creating your React app: create-react-app my-app --scripts-version @scope/react-scripts
.
A different option that some might prefer is react-app-rewired
: https://github.com/timarney/react-app-rewired - I haven't looked into this myself yet, but it seems like another good way of doing it that could potentially lessen the need to keep a fork of react-scripts
maintained.
create-react-app v2 (react-scrips >= 2.0.0)
works out the box with Relay Modern!
You just need babel-plugin-relay >= 1.7.0
, relay-compiler
and graphql
as dev dependencies to compile queries
Then you need a schema.graphql
files declaring your GraphQL types and of course react-relay
Before running start
you just have to compile any queries you might have added or changed inside of graphql tags. Simply add the script to your package.json which you can also run in watch mode:
"relay": "relay-compiler --src ./src --schema ./schema.graphql"
Fully working example here: https://github.com/kassens/relay-cra-example
If you don't want to maintain your own fork of react-scripts
, you can simply do the following:
babel-plugin-relay
$ yarn add babel-plugin-relay
./setup.js
file in the root of your projectconst fs = require('fs');
const path = require('path');
let file = path.resolve('./node_modules/babel-preset-react-app/index.js');
let text = fs.readFileSync(file, 'utf8');
if (!text.includes('babel-plugin-relay')) {
if (text.includes('const plugins = [')) {
text = text.replace(
'const plugins = [',
"const plugins = [\n require.resolve('babel-plugin-relay'),"
);
fs.writeFileSync(file, text, 'utf8');
} else {
throw new Error(`Failed to inject babel-plugin-relay in ${file}.`);
}
}
package.json
to run node setup
first"scripts": {
"build": "node setup && react-scripts build",
"test": "node setup && react-scripts test --env=jsdom",
"start": "node setup && react-scripts start"
}
For a complete Relay Modern + Create React App example (including routing) visit:
kriasoft
/react-static-boilerplate
on GitHub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With