使用tsc构建GraphQL+TypeScript+Node项目遇模块找不到问题
TypeScript构建GraphQL项目时的.graphql文件处理问题
问题表现
- 执行
npm run build编译项目后,运行npm run start会抛出模块找不到错误:
Error: Cannot find module './DomainOne/schema.graphql'
原因是编译生成的dist/GraphQL/index.js中仍保留了对.graphql文件的导入语句,但这些文件并未被复制到dist目录:
var schema_graphql_1 = __importDefault(require("./DomainOne/schema.graphql"));
- 手动将src下所有.graphql文件复制到dist对应目录后,TypeScript又抛出错误:
type Query is not a type in typescript
项目基础信息
技术栈
GraphQL、Node.js、Express、TypeScript
文件夹结构
src ├── Erros - 存放错误定义 ├── Graphql │ ├── index.ts - 导入所有.graphql文件 │ ├── schema.graphql │ ├── DomainOne │ │ ├── resolvers.ts │ │ ├── schema.graphql │ │ └── types.ts │ └── DomainTwo │ ├── resolvers.ts │ ├── schema.graphql │ └── types.ts ├── Routes - 路由配置 ├── Services - 后端API调用逻辑 ├── Utils - 工具函数 ├── global.d.ts ├── index.ts - Node+Express服务入口 └── ... ... package.json tsconfig.json
核心配置代码
package.json(脚本部分)
{ ... "scripts": { "build": "rimraf dist && tsc", "start": "node dist/index.js", ... }, ... }
tsconfig.json
{ "compilerOptions": { "target": "es5", "module": "commonjs", "lib": [ "dom", "es6", "ES2020" ], "allowJs": true, "sourceMap": true, "outDir": "dist", "removeComments": true, "strict": true, "noImplicitAny": true, "allowSyntheticDefaultImports": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": false, "resolveJsonModule": true }, "exclude": ["./tests/**/*.ts"], "include": ["./src/**/*.ts", "./**/*.graphql"] }
src/global.d.ts
// src/global.d.ts declare module '*.graphql' { import { DocumentNode } from 'graphql'; /* eslint-disable-next-line */ const value: DocumentNode; export = value; } declare module 'configuration-master' // 参考公开issue declare module 'apollo-server-core' { interface PluginDefinition { _: unknown } }
内容的提问来源于stack exchange,提问作者Owen Murphy
相关产品推荐
相关产品推荐

