Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

babel-plugin-import-graphql

detrohutt171.8kMIT2.8.1

Babel plugin to make .gql/.graphql files importable

babel-plugin, apollo, graphql, gql, extension, import, inline

readme

npm Version npm Downloads npm License donate

babel-plugin-import-graphql

Babel plugin enabling import syntax for .graphql and .gql files.

For users of the old package name (babel-plugin-inline-import-graphql-ast)
<summary>Deprecation/Migration notes</summary>

As of May 27, 2018, the babel-plugin-inline-import-graphql-ast package name is deprecated. Please use babel-plugin-import-graphql (NPM) instead.

Migrating to babel-plugin-import-graphql

Update your babel configuration

Update plugins array:

babel-plugin-inline-import-graphql-ast (or inline-import-graphql-ast) -> import-graphql.

Update your package.json file

Update the package name in devDependencies:

babel-plugin-inline-import-graphql-ast -> babel-plugin-import-graphql.

Make sure your version string is compatible:

The first correct version of babel-plugin-import-graphql is 2.4.4 so please make sure your version string matches that. For instance, "babel-plugin-import-graphql": "^2.0.0" is fine because of the caret.

If you've pinned to a specific version, you'll need to upgrade and pin to at least 2.4.4 or widen your version range to include it.

Congratulations, you're all set!


If you enjoy my package please star the GitHub repo or share on Twitter (and follow me for updates)!

Prerequisites

  • babel-core@^6.26.3 or @babel/core@^7.0.0-beta.40 (Lower betas may work but weren't tested)

  • graphql-tag@^2.1.0 (only if using the runtime option described below)

Install

$ yarn add -D babel-plugin-import-graphql

In .babelrc file:

{
  "plugins": ["import-graphql"]
}

Each time you modify a GraphQL file, the cache must be cleared for the changes to take effect.

If using node then the node_modules/.cache/babel-loader folder must be cleared. I recommend prepending the relevant script in your package.json and rerunning the script when you change a GraphQL file:

{
  "scripts": {
    "start": "rm -rf ./node_modules/.cache/babel-loader && node index.js"
  }
}

If using React Native then the metro cache must be reset every time you change a GraphQL file:

react-native start --reset-cache

Note: Windows users would need to use rimraf or another solution in place of rm -rf.

Basic Usage

...
import myQuery from './query.graphql'
...
export default graphql(myQuery)(myComponent)

Supported features

Schema files

Feature Description
Default import The entire source code for the file will act as the default export.
#import syntax Types, etc. in one GraphQL file can be imported into another GraphQL file using this syntax: #import "./types.graphql". These imports will be resolved recursively to any reasonable depth of files. Currently, all content in the named file will be imported and there is no way to import specific types. If you want that behavior, you can store a single type in each file.

Operation/fragment files

All variants of the import syntax are supported for non-schema files, except import './filename'.

Feature Description
Multiple operations/fragments per file Multiple operations (queries/mutations/subscriptions) and/or fragments can be placed in a single file. However, in this case you cannot use unnamed operations/fragments. For example, query { test } would need to be query someName { test }.
Default import The first or only operation/fragment in a file will act as the default export. However, for backwards compatibility reasons, if there are both operations and fragments in a file, the first operation will act as the default export.
Named imports All operations/fragments, including the default, act as named exports.
#import syntax Fragments in one GraphQL file can be imported into another GraphQL file using this syntax: #import "./fragment.graphql". These imports will be resolved recursively to any reasonable depth of files. Currently, all fragments in the named file will be imported and there is no way to import specific fragments. If you want that behavior, you can store a single fragment in each file.

Full example

Before (without this plugin):

ProductsPage.js

import React, { Component } from 'react'
import gql from 'graphql-tag'
import { graphql } from 'react-apollo'

class ProductsPage extends Component {
  render() {
    if (this.props.data.loading) return <h3>Loading...</h3>
    return <div>{`This is my data: ${this.props.data.queryName}`}</div>
  }
}

const productsQuery = gql`
  query products {
    products {
      productId
      name
      description
      weight
    }
  }
`

export default graphql(productsQuery)(ProductsPage)

After (with this plugin):

productFragment.graphql

fragment productFragment on Product {
  name
  description
  weight
}

productsQuery.graphql

#import "./productFragment.graphql"
query products {
  products {
    productId
    ...productFragment
  }
}

ProductsPage.js

import React, { Component } from 'react'
import { graphql } from 'react-apollo'
import myImportedQuery from './productsQuery.graphql'

class ProductsPage extends Component {
  render() {
    if (this.props.data.loading) return <h3>Loading...</h3>
    return <div>{`This is my data: ${this.props.data.queryName}`}</div>
  }
}

export default graphql(myImportedQuery)(ProductsPage)

Options

Option Type Default Description
nodePath String value of NODE_PATH environment variable Intended for use with react-app-rewire-inline-import-graphql-ast -- Used to allow resolution of absolute paths to your .gql/.graphql files. If you already have your NODE_PATH variable set in your environment, you don't need to set this option. Not currently respected by #import syntax.
runtime Boolean false Enabling this option requires graphql-tag to be installed as a peerDependency. -- Instead of inlining the parsed AST object, which is very large, this option inlines your GraphQL source code along with an import of the gql function from graphql-tag and parses your GraphQL source code with gql at runtime.
extensions Array [] Enables loading GraphQL SDL files that have a custom extension, e.g. '.prisma'
emitDeclarations Boolean false Enables emmitting .d.ts files next to GraphQL query/fragment source file.

For users of create-react-app

create-react-app users can use this package without ejecting via react-app-rewire-inline-import-graphql-ast

Credits

The behavior of this plugin is inspired by and mostly mirrors the graphql-tag Webpack loader

This package started out as a modified version of babel-plugin-inline-import

changelog

ChangeLog

v2.8.1 (January 2, 2021)

Fixes

  • Update lock files to patch vulnerabilites in production dependencies

v2.8.0 (January 2, 2021)

Features

  • Support import * from "..." syntax (Thanks @dfrankland)
  • Add emitDeclarations option to emit *.d.ts files next to source graphql files (Thanks @langpavel)

Fixes

  • Maintain support with node v12.3.0+ (Thanks @orkaplan)
  • Remove dependence on require.resolve to fix issues with node v12 (Thanks @VojtaSim)

Maintenance

  • Stop linting the build folder in editors

v2.7.0 (March 3, 2019)

Features

  • Add extensions option to allow parsing custom file types like .prisma (:clap: @DaBs)

v2.6.2 (June 29, 2018)

Fixes

  • Continue fixing bug with multiple imports in a schema file (Thanks @gregorycuellar)

v2.6.1 (June 29, 2018)

Fixes

  • Fix duplicate code when using multiple imports in one schema file (Thanks @gregorycuellar)

v2.6.0 (June 16, 2018)

Features

  • Add support for #import syntax in schema files

Maintenance

  • Improve Options table in README
  • Refactor existing tests and add new tests

v2.5.2 (June 8, 2018)

Fixes

  • Continue fixing compatibility with Babel 6

v2.5.1 (June 8, 2018)

Fixes

  • Fix compatibility issue with Babel 6

v2.5.0 (June 7, 2018)

Features

  • Reduce output size of AST ({ runtime: false }) by 30%+ :fire: (:clap: @loganfsmyth and @supukarmin)
  • Add new 'runtime' option for even smaller output :mag: (if enabled, 'graphql-tag' is a peerDependency)

Maintenance

  • Update all devDependencies :arrows_counterclockwise:
  • Improve the README :tada:

v2.4.4 (May 27, 2018)

Maintenance

  • Update copyright in LICENSE
  • Update deprecation/migration info in README.md
  • Update package name, author, and repository in package.json

v2.4.2, v2.4.3 (May 27, 2018) ** Don't use these **

Maintenance

  • Temporarily created a new repo on GitHub and published from that, but have now removed that repo and renamed the original repo instead.

v2.4.1 (May 27, 2018)

Maintenance

  • Deprecate this package in favor of babel-plugin-import-graphql (see README)

v2.4.0 (May 18, 2018)

Features

  • Add support for fragment-only files with multiple fragments
  • Add support for importing fragments from mixed files (containing fragments and operations)

v2.3.8 (May 15, 2018)

Fixes

  • Refactor plugin to not have direct dependency on @babel/core (hopefully fixing #30)
  • Update package-lock.json that was not updated for version 2.3.7

Maintenance

  • Automate updating of package-lock.json and yarn.lock
  • Remove undocumented requireGql export
  • Update all dependencies

v2.3.7 (April 26, 2018)

Maintenance

  • Update dependencies

v2.3.6 (March 30, 2018)

Fixes

  • Fix operation files with top level indentation being mistaken for schema files

Maintenance

  • Add regression tests for above fix

v2.3.5 (March 15, 2018)

Maintenance

  • Adjust code to conform to relevant breaking change in @babel/core@7.0.0-beta.41 (more forward-compatible solution to "bug" from #24)
  • Upgrade @babel/core dependency to 7.0.0-beta.42
  • Improve tests code

v2.3.4 (March 14, 2018)

Fixes

  • Pin versions of babel packages which were causing issue #24

Maintenance

  • Begin including package-lock.json file for users of NPM

v2.3.3 (March 9, 2018)

Fixes

  • Fix fragments inlining as raw text

Maintenance

  • Add regression test for above fix

v2.3.2 (March 9, 2018)

Fixes

  • Fix operations with fragments inlining as raw text

Maintenance

  • Add initial test for fragments

v2.3.1 (March 8, 2018)

Maintenance

  • Update all dependencies/devDependencies

v2.3.0 (March 8, 2018)

Features

  • Initial support for schema-like files

Maintenance

  • Fix typos in README

v2.2.0 (February 17, 2018)

Features

  • Multiple operations in a single GraphQL file

  • Named and namespace imports (can be mixed with default imports)

Maintenance

  • Update README.md

  • Upgrade all dependencies (including upgrading to Babel 7)

  • Add Jest and write initial tests covering import types

  • Improve, expand, and reconfigure toolchain (babel, eslint, prettier, lint-staged)

v2.1.2 (January 26, 2018)

Maintenance

  • Add "Known Issues" section to README.md

v2.1.1 (January 25, 2018)

Fixes

  • Revert changes to babel settings and babel dependencies

v2.1.0 (January 25, 2018)

Features

  • Add nodePath option

Fixes

  • Respect NODE_PATH environment variable

Maintenance

  • Remove leftover files and dependencies from babel-plugin-inline-import

v2.0.4 (December 7, 2017)

Fixes

  • Improve .gql file parsing to address issues with Windows and/or IDE settings (@OisinOKeeffe @Tzelon)

v2.0.3 (December 1, 2017)

Fixes

  • Utilize regex for more robust statement splitting (@Tzelon)

v2.0.2 (October 9, 2017)

Maintenance

  • Change graphql to a peer dependency and allow newer versions

v2.0.1 (September 23, 2017)

Note: this should have been a minor release rather than a patch release. Oops!

Features

  • Added support for nested fragments

  • Added support for Babel's resolveModuleSource option (@real34)

Fixes

  • Deduplicate fragments

v2.0.0 (July 22, 2017)

Breaking

  • Potentially removed Meteor support. Not sure it worked anyway and there's an alternative solution for .graphql files in Meteor.

  • Removed support for customizable extensions. This was undocumented and left over from the project I forked.

Features

  • <query>.loc.source is now available on the inlined query

Maintenance

  • Major rewrite. Code is now much smaller and more readable. (1 file, ~60 LOC)

  • Removed dependence on resolve package.

v1.3.3

First official release with Windows support

Updated README and CHANGELOG

v1.3.2

Test version(debugging Windows problems), published as @winfix tag

First version that works on Windows/Mac/Linux

v1.3.1

Test version(debugging Windows problems), published as @winfix tag

First working version on Windows, non-functional on Mac/Linux

v1.3.0

Test version(debugging Windows problems), published as @winfix tag

Initial attempt, non-functional

v1.2.3

Update name of Github repo

v1.2.2

Add required graphql dependency

v1.2.1

Update npm keywords

v1.2.0

Add support for GraphQL Fragments

Remove support for .raw and .text extensions(left over from forked project)

v1.1.1

Update forked README to reflect the new package

v1.1.0

Add support for .gql file extension

v1.0.1

First functional version

Add ability to import .graphql files as AST(only on Mac/Linux)

Fix package.json info

v1.0.0

Initial version. Bad publish, non-functional