leo*_*ger 9 typescript graphql
我有一个节点,使用 expressGraphql 的快速服务器。我试图在 a.graphql
或.gql
文件中声明 graphql 的类型定义,因为随着类型变大,读取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,
})
);
Run Code Online (Sandbox Code Playgroud)
我的graphql文件。//test.graphql
type Book {
message: String
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误,因为 Typescript
找不到模块“./test.graphql”。
我见过有人这样做:
const { makeExecutableSchema } = require('graphql-tools');
const schemaFile = path.join(__dirname, 'schema.graphql');
const typeDefs = fs.readFileSync(schemaFile, 'utf8');
const schema = makeExecutableSchema({ typeDefs });
Run Code Online (Sandbox Code Playgroud)
这是这样做的方式吗?
那么我需要配置打字稿才能导入和构建架构
您可以使用https://github.com/ardatan/graphql-import-node来解决这个问题,而无需使用 webpack。
使用yarn add graphql-import-node
或安装npm install --save graphql-import-node
,然后使用graphql-import-node/register
钩子(如果您使用的是 ts-node):
ts-node -r graphql-import-node/register index.ts
或者将其导入到文件的顶部,如下所示:
import "graphql-import-node";
Run Code Online (Sandbox Code Playgroud)
我在我的例子中选择了后者,因为我已经在测试中使用了ts-node/register
with 。mocha -r
您可能还需要添加"esModuleInterop": true
到tsconfig.json
.
AFAIK,有两种导入模式文件的方法,1)按照上面的描述直接读取文件,或者 2)将查询包装在导出的变量中。
// 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,
] });
Run Code Online (Sandbox Code Playgroud)