如何在没有 webpack 的打字稿节点项目中使用 .graphql [英] how to use .graphql in a typescript node project without webpack
问题描述
我有一个节点,使用 expressGraphql 的快速服务器.我试图在 .graphql
或 .gql
文件中声明 graphql 的类型定义,因为随着类型变大,读取 字符串变得困难代码>.
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,有两种导入模式文件的方法,1) 通过直接读取文件,或者 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屋!