You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:22:34