Babel GraphQL Import
Babel plugin to add the opportunity to use import
for importing *.graphql
files into your code with graphql-import
.
Examples
Before (without Babel-GraphQL-Import):
// server.js
// bad syntax highlighting, no syntax checking
const typeDefinitions = `
type Query {
testString: String
}
schema {
query: Query
}
`;
graphQLServer({
schema: [typeDefinitions],
...
});
Now (with Babel-GraphQL-Import):
// /some/schema.graphql
type Query {
testString: String
}
schema {
query: Query
}
// server.js
import schema from '/some/schema.graphql';
graphQLServer({
schema: [schema],
...
});
Note: both cases are equivalent and will result in similar code after Babel transpile them. Check How it works section for details.
Install
npm install babel-plugin-graphql-import --save-dev
Use
Add a .babelrc
file and write:
{
"plugins": [
"babel-plugin-graphql-import"
]
}
or pass the plugin with the plugins-flag on CLI
babel-node myfile.js --plugins babel-plugin-graphql-import
How it works
It inserts the content of the imported file by using importSchema
from graphq-import into the importing file, assigning it to a variable with the same identifier of the import statement, thus replacing the import statement and the file path by its resulting content from importSchema
.
Caveats
Babel does not track dependency between imported and importing files after the transformation is made. Therefore, you need to change the importing file in order to see your changes in the imported file spread. To overcome this:
- If you are using
babel-node
orbabel-register
, you can disable babel cache (BABEL_DISABLE_CACHE=1
). - If you are using webpack with
babel-loader
, you can use babel-inline-import-loader.