Skip to content

ADR-0002: Dual-Mode Package Consumption ​

Date: 2026-07-28 Status: Accepted

Context ​

The monorepo has two consumers with different module systems:

ConsumerModule SystemBuild Tool
apps/admin (Vue SPA)ESM, moduleResolution: bundlerVite
apps/server (NestJS)ESM (type: module), moduleResolution: bundlerSWC

2026-11-30 订正(ADR 0033):上表第二行原文是 「CJS, moduleResolution: node10」。server 已在 P0–P3 批次整批翻成 ESM,与前端共用 esnext / bundler 的模块语义 —— 两端的模块系统分歧消失,只剩「由谁构建、产物形态」 的差异(Vite 直读源码 vs SWC 产出 dist)。下表/下文凡写「后端读 CJS」的地方,都是 2026-11 之前的形态,保留作历史口径。

Packages consumed by both (@walnut/contract, @walnut/utils) need to work in both worlds.

Decision ​

Use package.json exports with a custom "source" condition:

json
{
  "exports": {
    ".": {
      "source": "./src/index.ts",
      "types": "./src/index.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs",
      "default": "./dist/index.cjs"
    }
  }
}
  • Frontend dev: Vite resolves "source" → raw .ts → instant HMR
  • Frontend prod: Vite bundles workspace source directly (no separate ESM build needed)
  • Backend: SWC resolves "import" → built ESM(2026-11 起;此前是 "require" → built CJS)
  • CJS consumers: Node 原生的 require 通道(apps/e2e 的 lib/protocol)解析 "require" → dist/*.cjs
  • IDE: TypeScript resolves "types" → source .ts

"source" not "development": Webpack's NODE_ENV=development also matches the "development" export condition. A scope-qualified name avoids this collision. (Vite RFC, Nx, and Turborepo docs all recommend this pattern.)

2026-11 变更(ADR 0033 Decision 5):"import" 从指回 src/index.ts 改成指向真 ESM 产物 dist/index.js。指回源码在本地符号链接下侥幸能跑,pnpm deploy 进镜像的 node_modules 后 Node 拒绝类型剥离,容器启动即失败(P0 的生产雷)。双格式 dist 由 tsdown 同批产出 (outExtensions 钉 .js / .cjs),"source" / "types" 仍指源码。

Alternatives considered ​

  • Source-only (JIT) for every package —— the backend cannot resolve TypeScript source from node_modules (Node does not strip types there), so a source-only package breaks at pnpm deploy / first import.
  • CJS-only build —— the frontend loses HMR and pays build latency.
  • tsconfig paths only —— it works on both sides, but leaves 4 files to maintain and does not scale.

Consequences ​

  • CJS + ESM 双构建(2026-11 起;原文是「Only CJS is built」):tsdown 的 format: ['cjs', 'esm'] 同批产出 dist/*.cjs 与 dist/*.js,outExtensions 把 ESM 钉成 .js(type: module 的包里 tsdown 默认给 .mjs,与手写 exports 对不上)。前端仍读源码, 不需要为 Vite 单独产出。
  • Backend packages (@walnut/contract, @walnut/utils) need @types/node for build-time type checking.
  • Adding a new shared package requires: tsdown.config.ts(双格式构建)+ tsconfig.json + package.json exports.
  • 跨包 @walnut/* 只走 pnpm workspace 符号链接 + package.json exports,不写 tsconfig paths (ADR 0012 Decision 4);server 内部的 @walnut-server/* 由 Nest CLI 把根 tsconfig 的 paths 注入 SWC(ADR 0032), .swcrc 不再手抄别名。

基于 MIT 许可发布