Parcel 如何识别 .graphql 文件并自动生成 TypedDocumentNode?请指出所需插件与 ts 类型输出路径。
解读
面试官想验证三件事:
- 你是否知道 Parcel 的“零配置”并非“零插件”,遇到 GraphQL 必须显式安装转换器;
- 你是否清楚 TypedDocumentNode 需要把 GraphQL 操作文本同时转成「运行时对象 + TypeScript 类型」,而 Parcel 的插件体系正好把这两件事串在一条管道里;
- 你是否能在真实 CI/CD 场景下说出产物路径、缓存策略与类型检查闭环,而不是只背官网示例。
国内项目普遍要求「类型即文档」,答不出类型文件落盘位置会被直接判定为“只跑过 Demo”。
知识点
- Parcel 的“Transformer”与“Resolver”分工:Transformer 负责把源文件转译为 JS 模块,Resolver 决定依赖如何被拉取。
- @parcel/transformer-graphql 只产出「运行时 JS 对象」,不含类型;必须再串 @parcel/transformer-typescript-types 或社区插件 parcel-transformer-graphql-typed 才能同时生成 .d.ts。
- TypedDocumentNode 由 graphql-typed-document-node 提供,核心是把 Query/Mutation/Subscription 的 AST 映射成 TS 泛型,实现“写一次 GraphQL,类型零成本下沉到组件”。
- 产物路径规则:
- 运行时:dist/xxx.js(由 Parcel 主流程决定,与 entry 同名)
- 类型:dist/types/__parcel__graphql/[hash].d.ts(@parcel/transformer-typescript-types 默认)或 parcel-cache/graphql-typed/[name].d.ts(社区插件可配置)
- 国内 Monorepo 常把类型文件统一收拢到 packages/foo/src/types/graphql.d.ts,需要在 .parcelrc 里显式写
"graphQLTypedOutput": "./src/types",否则缓存目录在 node_modules/.parcel-cache,CI 会清掉。 - 缓存键包含文件内容哈希与插件版本,升级 @parcel/transformer-graphql 必须手动 rm -rf .parcel-cache,否则会出现“类型已改但旧文件不更新”的幽灵 Bug。
答案
步骤如下:
-
安装依赖
npm i -D @parcel/transformer-graphql @parcel/transformer-typescript-types graphql-typed-document-node
(Yarn 国内源加 --registry=https://registry.npmmirror.com) -
配置 .parcelrc
{
"extends": "@parcel/config-default",
"transformers": {
"*.graphql": ["@parcel/transformer-graphql", "@parcel/transformer-typescript-types"]
}
}
如果希望类型文件落盘到 src/types,需写社区插件 parcel-transformer-graphql-typed,并在插件参数里指定"outputPath": "./src/types"。 -
源码中直接导入
import { TypedDocumentNode } from 'graphql-typed-document-node';
import * as GetUser from './getUser.graphql';
type Vars = GetUser.GetUserQueryVariables;
type Data = GetUser.GetUserQuery;
const document: TypedDocumentNode<Data, Vars> = GetUser; -
运行 parcel build src/index.html —dist-dir dist
产物:- 运行时:dist/getUser.xxxxx.js(模块 ID)
- 类型:dist/types/__parcel__graphql/getUser.d.ts
内容示例:
export declare const GetUserQuery: import("graphql-typed-document-node").TypedDocumentNode<GetUserQuery, GetUserQueryVariables>;
-
CI 验证
在 tsconfig.json 里加 "include": ["src//*", "dist/types//*"],tsc --noEmit 即可把 GraphQL 类型纳入整体类型检查,防止后端字段下线而前端无感知。
拓展思考
-
如果团队使用 GraphQL Code Generator 做“集中式类型”,而 Parcel 做“构建时类型”,两者会争同一份 schema,如何防止双写?
答:在 pnpm-workspace 里把 schema.graphql 抽成单独包,设 resolve.alias,让 Parcel 与 Code Generator 同读一份文件,保证哈希一致。 -
微前端场景下,子应用 A 的 TypedDocumentNode 如何被主应用 B 复用?
答:把子应用 A 的 GraphQL 类型文件声明为 “types”: “dist/types/index.d.ts”,主应用 B 通过三斜指令 /// <reference types="a/types" /> 引入,避免再次编译。 -
国内网络拉取远端 schema 经常超时,如何本地兜底?
答:在 prebuild 脚本里加 “get-graphql-schema http://api.xxx.com/graphql > schema.graphql”,同时把 schema.graphql 写入 git-lfs,CI 无法外网时直接读缓存,Parcel 侧无感。