在 Apollo Server v4 中,模块导入路径解析错误通常是由 TypeScript 编译器的配置问题造成的。以下是解决该问题的步骤:
npm install typescript apollo-server-express
tsconfig.json
文件,该文件用于配置 TypeScript 编译器。在项目根目录下创建该文件,并添加以下内容:{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"outDir": "./dist",
"target": "es6",
"lib": ["es6", "dom"],
"sourceMap": true,
"strict": true,
"module": "commonjs",
"resolveJsonModule": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}
上述配置中的 "include": ["src"]
表示只编译 src
目录下的 TypeScript 文件。如果你的项目结构不同,请相应地修改该配置。
.ts
扩展名。例如,假设你的入口文件是 index.ts
,内容如下:import { ApolloServer, gql } from 'apollo-server-express';
// 其他导入语句和代码
// 创建 ApolloServer 实例
const server = new ApolloServer({ /* 配置项 */ });
// 其他代码
// 启动服务器
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
package.json
文件中添加一个 scripts
字段,用于启动 TypeScript 编译器和运行服务器。例如,可以添加以下内容:{
"scripts": {
"start": "tsc && node dist/index.js"
}
}
上述配置中的 dist/index.js
是编译后的 JavaScript 文件路径。如果你的项目结构不同,请相应地修改该配置。
npm start
现在,你应该能够解决 Apollo Server v4 中的模块导入路径解析错误,并成功启动服务器。