ADR-0002: Dual-Mode Package Consumption
Date: 2026-07-28 Status: Accepted
Context
The monorepo has two consumers with different module systems:
| Consumer | Module System | Build Tool |
|---|---|---|
apps/admin (Vue SPA) | ESM, moduleResolution: bundler | Vite |
apps/server (NestJS) | ESM (type: module), moduleResolution: bundler | SWC |
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:
{
"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 atpnpm 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/nodefor build-time type checking. - Adding a new shared package requires:
tsdown.config.ts(双格式构建)+tsconfig.json+package.jsonexports. - 跨包
@walnut/*只走 pnpm workspace 符号链接 +package.jsonexports,不写 tsconfig paths (ADR 0012 Decision 4);server 内部的@walnut-server/*由 Nest CLI 把根 tsconfig 的paths注入 SWC(ADR 0032),.swcrc不再手抄别名。