如何在没有Webpack的打字稿节点项目中使用.graphql [英] how to use .graphql in a typescript node project without webpack

查看:56
本文介绍了如何在没有Webpack的打字稿节点项目中使用.graphql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个节点,使用expressGraphql的Express服务器.我正在尝试在 .graphql .gql 文件中声明graphql的类型定义,因为随着类型的增加,很难读取 string.

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.

这是我所拥有的:

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,
    })
);

我的graphql文件.//test.graphql

My graphql file. //test.graphql

type Book {
    message: String
}

我收到一个错误,因为打字稿

I get an error because Typescript

找不到模块'./test.graphql'.

Cannot find module './test.graphql'.

我见过有人这样做:

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

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

const schema = makeExecutableSchema({ typeDefs });

这是这样做的方式吗?

所以我需要配置打字稿才能导入并构建模式

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

推荐答案

AFAIK,有两种方法可以导入架构文件,一种是通过如上所述直接读取文件,另一种是2)通过将查询包装在导出文件中变量.

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,
] });

这篇关于如何在没有Webpack的打字稿节点项目中使用.graphql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆