Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use .graphql in a typescript node project without webpack

I have a node, express server using expressGraphql. I am trying to declare a type definition for graphql in a .graphql or .gql file, because as the type gets larger, it becomes difficult to read the string.

Here is what I have:

import testQuery from './test.graphql';

import routes from "./routes";

import { buildSchema } from "graphql";

const schema = buildSchema(testQuery);

// Root resolver
const root = {
    message: () => "Hello World!",
};

app.use(
    "/api/graphql",
    expressGraphQL({
        schema,
        graphiql: true,
    })
);

My graphql file. //test.graphql

type Book {
    message: String
}

I get an error because Typescript

Cannot find module './test.graphql'.

I have seen people doing this:

const { makeExecutableSchema } = require('graphql-tools');

const schemaFile = path.join(__dirname, 'schema.graphql');
const typeDefs = fs.readFileSync(schemaFile, 'utf8');

const schema = makeExecutableSchema({ typeDefs });

Is this the way of doing it?

So what do I need to to config typescript to be able to import, and build the schema

like image 656
leogoesger Avatar asked Jul 25 '18 18:07

leogoesger


People also ask

Does GraphQL work with TypeScript?

Using TypeScript and GraphQL ensures that static typing exists all through your application. Without TypeScript, you can still create query types with GraphQL.


2 Answers

You can use https://github.com/ardatan/graphql-import-node to solve this without webpack.

Install with yarn add graphql-import-node or npm install --save graphql-import-node and then either use the graphql-import-node/register hook (if you're using ts-node):

ts-node -r graphql-import-node/register index.ts

Or import it in your file right at the top like this:

import "graphql-import-node";

I chose the later in my case because I already used ts-node/register with mocha -r for my tests.

You also may need to add "esModuleInterop": true to your compilerOptions in tsconfig.json.

like image 166
allesklarbeidir Avatar answered Sep 27 '22 21:09

allesklarbeidir


AFAIK, there are two ways to import schema files, either 1) by reading the file directly as you describe above, or 2) by wrapping the queries in exported variables.

// bookSchema.ts <- note the file extension is .ts instead of .graphql
export default `
  type Book {
    message: String
  }
`

// anotherSchema.ts <- note the file extension is .ts instead of .graphql
export default `
  type User {
    name: String
  }
`

// main.ts
import bookSchema from 'bookSchema';
import anotherSchema from 'anotherSchema';

const schema = makeExecutableSchema({ typeDefs: [
  bookSchema,
  anotherSchema,
] });
like image 29
Mikael Lirbank Avatar answered Sep 27 '22 19:09

Mikael Lirbank