Babel Inline Import GraphQL AST
Babel plugin allowing you to import
.graphql
and .gql
files. The code is pre-parsed by gql
from graphql-tag
and the GraphQL AST object is inserted into your code at transpile time.
Important note
While this package is intended as an alternative to graphql-tag/loader, it does NOT currently support importing fragments with #import
. Work on this is underway.
Known use cases
Somewhat replaces graphql-tag/loader
in projects where Webpack is unavailable(i.e. NextJS)
Examples
Before (without babel-plugin-inline-import-graphql-ast):
...
import { gql } from 'react-apollo'
class ProductsPage extends React.Component {
...
}
const productsQuery = gql`
query products {
products {
productId
name
description
weight
}
}
`
export default graphql(productsQuery)(ProductsPage)
Now (with babel-plugin-inline-import-graphql-ast):
query products {
products {
productId
name
description
weight
}
}
...
import myImportedQuery from './productsQuery.graphql'
class ProductsPage extends React.Component {
...
}
export default graphql(myImportedQuery)(ProductsPage)
Note: both cases are equivalent and will result in similar code after Babel transpiles them. Check How it works section for details.
Install
yarn add -D babel-plugin-inline-import-graphql-ast
Use
Add a .babelrc
file and write:
{
"plugins": [
"babel-plugin-inline-import-graphql-ast"
]
}
or pass the plugin with the plugins-flag on CLI
babel-node myfile.js --plugins babel-plugin-inline-import-graphql-ast
By default, Babel-Inline-Import is compatible with the following file extensions:
Customize
If you want to enable different file extensions, you can define them in your .babelrc
file
{
"plugins": [
["babel-plugin-inline-import", {
"extensions": [
".json",
".sql"
]
}]
]
}
How it works
When you import
a .graphql
or .gql
file, it is parsed into a GraphQL AST object by the gql
function from graphql-tag
. This AST object is inserted directly into the importing file, in a variable with the name defined in the import statement. The import should be treated as a default import(name whatever you want; no braces necessary)
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, you can:
- Disable babel cache (
BABEL_DISABLE_CACHE=1
)
Also make sure that your task runner is watching for changes in the imported file as well. You can see it working here.
Credits
This package is a modified version of babel-plugin-inline-import