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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:55:17