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

Lerna Monorepo中导入普通Enum运行报错,寻求无需改用const enum的方案

Lerna Monorepo中导入enum/class运行时报错问题

我搭建了一个Lerna Monorepo,包含以下两个包:

  • @whatever/types:仅含一个index.ts文件:
export enum PetKind {
  Dog,
  Cat,
}

export type Pet = {
  kind: PetKind
}
  • @whatever/api:仅含一个index.ts文件:
import { Pet, PetKind } from '@whatever/types'

const pet: Pet = {
  kind: PetKind.Dog
}

这是一个Node.js应用,因此在package.json中设置了:

"type": "module"

可以成功编译@whatever/api,但运行编译后的脚本时会出现如下错误:

import { PetKind } from '@whatever/types';
         ^^^^^^^ SyntaxError: Named export 'PetKind' not found.

经过多次尝试后发现,该问题由导入enum导致:移除enum后报错消失;将enum替换为const enum(同时将@whatever/api的tsconfig.json中isolatedModules设为false)也能解决问题:

// 此写法可行
import { Pet } from '@whatever/types'

const pet: Pet = {
  kind: 0
}
// 此写法也可行
export const enum PetKind {
  Dog,
  Cat,
}

export type Pet = {
  kind: PetKind
}

我使用的tsconfig配置如下:

  • @whatever/types的配置:
{
  "compilerOptions": {
    "lib": ["esnext"],
    "types": [],
    "target": "es2020",
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "declaration": true,
    "rootDir": "./src",
    "outDir": "./build"
  },
  "include": ["./src"]
}
  • @whatever/api的配置:
{
  "compilerOptions": {
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "noEmit": false,
    "declaration": true,
    "types": ["node"],
    "lib": ["esnext"],
    "target": "es2020",
    "module": "esnext",
    "moduleResolution": "node",
    "isolatedModules": true, // 尝试`const enum`时我会将其改为false
    "experimentalDecorators": true,
    "rootDir": "./src",
    "outDir": "./build",
    "typeRoots": ["@whatever/types"]
  },
  "include": ["./src"]
}

我不想毫无理由地使用const enum,据我了解,该写法通常仅在需要减小包体积时才推荐使用,而我的场景并不需要。请问有没有其他解决办法?

更新: 我发现问题可能在于无法从@whatever/api导入任何编译后的代码,我尝试从@whatever/types导出class,导入时也出现了相同的错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:50:24