GraphQL服务器启动失败:找不到dist/index.js模块求助
无法启动Apollo Server:找不到dist/index.js模块错误
我是GraphQL新手,跟着Apollo官网入门文档操作,严格按步骤执行后服务器启动失败,收到错误:
Error: Cannot find module '...graphql-fcc-example\dist\index.js'
我的项目src文件夹下有index.ts和schema.ts文件,相关代码及配置如下:
index.ts
// For these to work, type="module" import { ApolloServer } from '@apollo/server'; // to connect with the server import { startStandaloneServer } from '@apollo/server/standalone'; // to start import { typeDefs } from './schema'; import db from '../database/_db'; const resolvers = { Query: { games() { return db.games; }, reviews() { return db.reviews; }, authors() { return db.authors; } } } const server = new ApolloServer({ typeDefs, resolvers }) const { url } = await startStandaloneServer(server, {listen: {port: 4000 }}); console.log("server ready at port", 4000);
schema.ts
export const typeDefs = `#graphql type Game { id: ID!, title: String!, platform: [String!]! } type Review { id: ID!, rating: Int!, content: String! } type Author { id: ID!, name: String!, verified: Boolean! } type Query { games: [Game] authors: [Author] reviews: [Review] } `
package.json
{ "name": "graphql-fcc-example", "version": "1.0.0", "main": "index.js", "scripts": { "compile": "tsc", "start": "npm run compile && node ./dist/index.js" }, "keywords": [], "author": "", "license": "ISC", "type": "module", "dependencies": { "@apollo/server": "^4.10.0", "graphql": "^16.8.1", "nodemon": "^3.0.3" }, "devDependencies": { "@types/node": "^20.11.16", "typescript": "^5.3.3" }, "description": "" }
tsconfig.json(注意:当前配置错误,内容与package.json重复)
{ "name": "graphql-fcc-example", "version": "1.0.0", "main": "index.js", "scripts": { "compile": "tsc", "start": "npm run compile && node ./dist/index.js" }, "keywords": [], "author": "", "license": "ISC", "type": "module", "dependencies": { "@apollo/server": "^4.10.0", "graphql": "^16.8.1", "nodemon": "^3.0.3" }, "devDependencies": { "@types/node": "^20.11.16", "typescript": "^5.3.3" }, "description": "" }
我已尝试的解决方法:
- 执行
npm run compile确认TypeScript编译成功,编译过程无报错 - 检查项目文件夹结构
- 重新执行
npm install下载依赖 - VSCode未检测到代码语法错误
解决方案建议
- 修复tsconfig.json配置
当前tsconfig.json完全是package.json的内容,这是核心问题。TypeScript需要正确的编译配置才能将src下的.ts文件输出到dist目录。替换为以下配置:
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "node", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }
outDir: 指定编译后的文件输出到dist目录rootDir: 指定TypeScript源文件的根目录为srcinclude: 告诉TypeScript编译src下的所有文件
验证编译输出
删除现有dist文件夹,重新执行npm run compile,检查dist目录是否生成,且包含index.js、schema.js等编译后的文件。检查文件路径兼容性
由于package.json中设置了"type": "module",确保编译后的ES模块路径正确:
- index.ts中
import db from '../database/_db',确认database文件夹在项目根目录,且_db文件(如_db.js或_db.ts)存在并正确导出数据。
- 重新启动服务器
完成上述修复后,执行npm start,确认服务器正常启动。
内容的提问来源于stack exchange,提问作者Vanshita Rohela
相关产品推荐
相关产品推荐

