如何一次性导出所有类名到 JSON 供服务端渲染使用?
解读
面试官真正想确认的是:
- 你是否理解 PostCSS 的“AST 遍历”能力,而不仅仅把 PostCSS 当成 Autoprefixer 的壳;
- 能否在构建阶段就把“样式-类名”映射沉淀成静态 JSON,让 Node 层(或 Go、Java 等)在服务端渲染(SSR)时无需再解析 CSS,直接按 key 取类名,避免 hydration 错配;
- 是否熟悉国内主流场景:Webpack/Vite + React/Vue + 同构直出,以及 CSS Modules 在其中的定位;
- 对性能、缓存、命名冲突、source-map 友好性有没有工程化经验。
一句话:用 PostCSS 插件在编译期把“最终生效的类名”收集并序列化到磁盘,供运行时快速读取。
知识点
- PostCSS 插件八股:
module.exports = (opts = {}) => { return { postcssPlugin: 'xxx', Once(root, { result }) { ... } } } - AST 节点类型:
rule.selector字符串需用 postcss-selector-parser 二次解析,才能准确拿到.class而非#id、:pseudo等; - CSS Modules 的
exportGlobals与generateScopedName:国内项目 90% 用-[local]-[hash:5]规则,必须保证 JSON 中的 key 与 JS 中import styles from './index.module.css'的映射一致; - 文件写盘时机:必须在
OnceExit阶段,等全部插件链执行完、类名已固化后再写;否则 cssnano 可能合并选择器导致遗漏; - 缓存与增量:Webpack5 持久缓存开启后,插件需声明
result.messages.dependencies与result.messages.assets,否则缓存会跳过; - 多入口场景:monorepo 下常有 A、B 两个子包共用
base.module.css,需按入口或 chunk 维度输出多份 JSON,避免类名重复覆盖; - 服务端读取性能:JSON 文件小于 50 kB 时直接
require进内存,更大则走fs.readFileSync+JSON.parse并做 LRU 缓存; - 安全:类名中可能含
\200b零宽空格或 emoji,需做JSON.stringify默认转义,防止 Node 层解析报错。
答案
-
安装依赖
pnpm add -D postcss-selector-parser -
编写插件
postcss-export-classes-to-json.jsconst fs = require('fs'); const path = require('path'); const selectorParser = require('postcss-selector-parser'); module.exports = (opts = {}) => { const { outputPath = 'dist/classMap.json', transform = (name) => name, // 允许外部自定义 key 转换 filter = () => true // 允许过滤 } = opts; const classSet = new Set(); return { postcssPlugin: 'postcss-export-classes-to-json', Once(root, { result }) { root.walkRules((rule) => { // 跳过 @keyframes、@media 等嵌套 if (rule.parent && rule.parent.type === 'atrule') return; selectorParser((selectors) => { selectors.walkClasses((node) => { const raw = node.value; if (filter(raw)) classSet.add(transform(raw)); }); }).processSync(rule.selector); }); }, OnceExit(root, { result }) { const map = Array.from(classSet).reduce((acc, cls) => { acc[cls] = cls; // 如需要可再做 value 映射 return acc; }, {}); fs.mkdirSync(path.dirname(outputPath), { recursive: true }); fs.writeFileSync(outputPath, JSON.stringify(map, null, 2), 'utf-8'); // 告诉 Webpack5 这是构建产物 result.messages.push({ type: 'dependency', plugin: 'postcss-export-classes-to-json', file: outputPath, parent: result.opts.from }); } }; }; module.exports.postcss = true; -
在
postcss.config.js里插入该插件,并保证在 CSS Modules 之后、cssnano 之前:module.exports = { plugins: [ require('postcss-modules')({ generateScopedName: '[name]__[local]--[hash:base64:5]' }), require('./postcss-export-classes-to-json')({ outputPath: 'build/server/classMap.json' }), require('autoprefixer'), ...(process.env.NODE_ENV === 'production' ? [require('cssnano')] : []) ] }; -
构建完成后,Node 层直出代码只需:
const classMap = require('../build/server/classMap.json'); function cx(name) { return classMap[name] || name; }
至此,所有类名一次性导出为 JSON,服务端渲染零运行时开销,hydration 安全对齐。
拓展思考
- 如果项目使用 Tailwind,类名是动态拼接的(如
p-${size}),AST 阶段无法枚举,此时应改用 “PurgeCSS + 安全列表” 方案,而非本插件; - 微前端场景,子应用独立构建,父应用需要合并多份 JSON,可在 CI 最后一步用 Node 脚本做
Object.assign并去重; - 若要支持“主题切换”,可把类名按主题拆成多份 JSON,服务端根据请求头
Cookie: theme=dark选择对应文件; - 对于“原子化 CSS” 与 “传统 BEM” 混写的老项目,可在插件里加白名单正则,只导出 BEM 类名,原子化类名走运行时压缩;
- 未来 CSS @scope、@layer 语法落地后,选择器结构会更复杂,需升级
postcss-selector-parser到 v7 以上,并考虑层权重对类名合并的影响。