Fastify+TypeScript项目导入fastify-openapi-glue遇ERR_REQUIRE_ESM错误
导入fastify-openapi-glue时的ESM兼容问题
我在基于TypeScript的Fastify项目中尝试导入fastify-openapi-glue库时,出现了Error [ERR_REQUIRE_ESM]错误。相关代码及配置如下:
routes.ts 文件
/* eslint-disable node/no-unsupported-features/es-syntax */ import { FastifyInstance } from 'fastify'; // import openapiGlue from 'fastify-openapi-glue'; // const openapiGlue = await import("fastify-openapi-glue"); import { Service } from '../controllers/service'; async function loadOpenapiGlue() { const openapiGlueModule = await import('fastify-openapi-glue'); return openapiGlueModule.default; } const options = { specification: './openapi.yaml', service: new Service() }; export default async (app: FastifyInstance): Promise<void> => { const openapiGlue = await loadOpenapiGlue(); app.register(openapiGlue, options); };
tsconfig.json 文件
{ "ts-node": { "require": ["tsconfig-paths/register"] }, "compilerOptions": { "alwaysStrict": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "removeComments": true, "lib": ["ES2020"], "module": "commonjs", "moduleResolution": "node", "noFallthroughCasesInSwitch": true, "noImplicitReturns": true, "noImplicitThis": true, "noUnusedLocals": true, "noUnusedParameters": true, "baseUrl": "./src", "rootDirs": ["src"], "outDir": "dist", "plugins": [], "resolveJsonModule": true, "skipLibCheck": true, "strict": true, "strictNullChecks": true, "target": "ES2020", "types": ["node", "jest"], "paths": { "@/*": ["*"] } }, "include": ["src"], "exclude": ["node_modules", "dist"] }
注意:按照建议将tsconfig.json中的"module"改为"ES2022"后,又出现了SyntaxError: Cannot use import statement outside a module错误。
内容的提问来源于stack exchange,提问作者Rahul Kumar
相关产品推荐
相关产品推荐

