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

创建首个Turbo Repo日志包遇导入失败:模块类型不兼容

解决Turbo Repo中ES模块与CommonJS模块的导入冲突问题

问题根源

你的@repo/logger包通过"type": "module"声明为ES模块,但apps/api项目默认是CommonJS模块(未配置"type": "module")。Node.js禁止CommonJS模块同步导入ES模块,因此触发了导入错误。


方案一:统一为ES模块(推荐长期维护)

将API项目转为ES模块,与日志包保持一致:

  1. 修改apps/api/package.json,添加"type": "module"字段:
{
  "name": "api",
  "version": "1.0.0",
  "type": "module", // 新增这行
  "description": "",
  "main": "index.ts",
  // 其他原有内容保持不变
}
  1. 调整API项目的tsconfig.json(若不存在则新建),确保编译输出ES模块:
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "outDir": "dist",
    "rootDir": "src",
    // 继承原有配置或添加其他必要选项
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}
  1. 替换ts-node为tsx(ES模块友好的TypeScript运行工具):
    • 先安装依赖:
      npm install -D tsx
      
    • 更新apps/api/package.json的脚本:
      {
        "scripts": {
          "build": "tsc",
          "start": "node dist/index.js",
          "dev": "tsx src/index.ts", // 替换原ts-node命令
          "test": "echo \"Error: no test specified\" && exit 1"
        }
      }
      

方案二:保持CommonJS,动态导入日志包(临时兼容)

如果不想修改模块系统,可将同步导入改为动态导入:

修改apps/api/src/index.ts:

// src/index.ts
import dotenv from "dotenv";
import express, { Express, Request, Response } from "express";

dotenv.config();

// 声明logger类型
let logger: typeof import("@repo/logger").logger;

// 动态导入日志包并启动服务
(async () => {
  const loggerModule = await import("@repo/logger");
  logger = loggerModule.logger;

  const app: Express = express();
  const port = process.env.PORT || 3000;

  app.get("/", (req: Request, res: Response) => {
    logger.info("Hello world");
    res.send("Express + TypeScript Server");
  });

  app.listen(port, () => {
    console.log(`[server]: Server is running at http://localhost:${port}`);
  });
})();

内容的提问来源于stack exchange,提问作者joshk132

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:43:13