VitorLuizC / graphql-raw-loader

:meat_on_bone: With Webpack, loads GraphQL files as raw strings and handle it's import directive & comment statement.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

GraphQL raw loader

Build Status

Load GraphQL files as raw strings and handle it's import directive & comment statement.

Installation

Install it using NPM/Yarn.

# using NPM
npm i -D graphql-raw-loader

# using Yarn
yarn add graphql-raw-loader --dev

Configuration

Add graphql-raw-loader to your webpack configuration:

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.(graphql|gql)$/,
        loader: 'graphql-raw-loader'
      }
    ]
  }
}

Usage example

fragment UserProfile on User {
  # Some fields.
}
query Users {
  users () {
    ...UserProfile @import(from: "./UserProfile.graphql")
  }
}
import query from './User.graphl'

export const getUsers = async () => {
  const response = await fetch('/api/graphql', {
    body: JSON.stringify({ query }),
    headers: {
      'Content-Type': 'application/json',
    },
  })
  const users = await response.json()
  return users
}

Importing on GraphQL

Officially there's no way to import GraphQL files inside each other. Other loaders fixed it by parsing import statement inside a comment.

Also, theres a thread about implementing import statements on GraphQL. One of the best suggestions is about using a directive to import fragments.

This loader supports both ways. 😎

Using comment import statement

# import "./UserDataFragment.graphql"
# The comment statement above is importing a file with UserDataFragment fragment
# inside it.

query Users {
  users (is_active: True) {
    data {
      ...UserDataFragment
    }
  }
}

Using @import directive

query Users {
  users (is_active: True) {
    data {
      ...
    }
    ...PaginationFragment @import(from: "./PaginationFragment.graphql")
    # The directive above is importing a file with PaginationFragment fragment
    # inside it.
  }
}

About

:meat_on_bone: With Webpack, loads GraphQL files as raw strings and handle it's import directive & comment statement.

License:MIT License


Languages

Language:JavaScript 60.1%Language:TypeScript 39.9%