Home

Awesome

babel-plugin-graphql

Babel plugin that compile GraphQL tagged template strings.

Issues related to GraphQL parsing should be reporter on graphql-parser issue-tracker.

Install

npm install --save-dev babel-plugin-graphql

Usage

Run:

babel --plugins graphql script.js

Or add the plugin to your .babelrc configuration:

{
  "plugins": [ "graphql" ]
}

Note: Due to current API limitations you need to enable es7.objectRestSpread transformer or stage 1 transformers.

Example

The plugin will compile the following code:

const IMAGE_WIDTH = 80
const IMAGE_HEIGHT = 80

const PostFragment = graphql`
  {
    post {
      title,
      published_at
    }
  }
`

const UserQuery = graphql`
  {
    user(id: <id>) {
      nickname,
      avatar(width: ${IMAGE_WIDTH}, height: ${IMAGE_HEIGHT}) {
        url
      },
      posts(first: <count>) {
        count,
        edges {
          node {
            ${ PostFragment() }
          }
        }
      }
    }
  }
`

into:

var IMAGE_WIDTH = 80;
var IMAGE_HEIGHT = 80;

var PostFragment = function PostFragment(params) {
  return {
    fields: {
      post: {
        fields: {
          title: {},
          published_at: {}
        }
      }
    }
  };
};

var UserQuery = function UserQuery(params) {
  return {
    fields: {
      user: {
        params: {
          id: params.id
        },
        fields: {
          nickname: {},
          avatar: {
            params: {
              width: IMAGE_WIDTH,
              height: IMAGE_HEIGHT
            },
            fields: {
              url: {}
            }
          },
          posts: {
            params: {
              first: params.count
            },
            fields: {
              count: {},
              edges: {
                fields: {
                  node: {
                    fields: _extends({}, PostFragment().fields)
                  }
                }
              }
            }
          }
        }
      }
    }
  };
};