如何处理小程序特有的文件类型?
解读
面试官抛出这道题,核心想验证三件事:
- 你是否真的在小程序项目里落地过 Husky,而不是只玩过 Demo;
- 面对“非标准”文件,你能否把 ESLint/Prettier/测试链路无缝串起来;
- 你对国内小程序生态(微信、支付宝、字节、百度)的构建差异有没有体感。
回答时要把“识别文件 → 匹配规则 → 调用对应工具 → 缓存提速 → 兼容 Windows 中文路径”完整闭环,并给出可落地的代码片段,让面试官一听就知道“这人背过真实锅”。
知识点
- 小程序特有文件:
.wxml / .axml / .ttml / .swan、.wxss / .acss / .ttss、.wxs / .sjs、.json(page.json、ext.json、plugin.json)、.ts 但带 wx 全局类型。 - 各工具链现状:
- wxml/axml 没有官方 parser,社区用 @wxml/parser 或 prettier-plugin-wxml;
- wxss/acss 完全兼容 CSS,可直接用 stylelint + postcss;
- wxs/sjs 是阉割版 JS,ESLint 需要自定义 parser(eslint-parser-wxs);
- json 文件需校验 schema,可用 @apidevtools/json-schema 或微信官方的 miniprogram-linter。
- Husky 8.x 以后只负责“触发”,逻辑全写在 lint-staged 配置里;
- 国内团队 90% 用 Windows,路径含中文、空格,glob 要加引号;
- 大仓库需用 eslint --cache、stylelint --cache,并把 .eslintcache 加入 .gitignore;
- CI 场景要加 HUSKY=0 跳过,避免 Docker 里装 husky 失败。
答案
“我在上一家公司负责 200+ 小程序的 monorepo,husky 是这样处理特有文件的:
第一步,依赖到位:
npm i -D husky lint-staged @wxml/parser prettier-plugin-wxml eslint-parser-wxs stylelint stylelint-config-standard
第二步,package.json 里声明 lint-staged:
"lint-staged": {
".{wxml,axml,ttml,swan}": ["prettier --write", "node scripts/lint-wxml.js"],
".{wxss,acss,ttss}": ["stylelint --fix --cache"],
".{wxs,sjs}": ["eslint --fix --cache --parser eslint-parser-wxs"],
".{js,ts}": ["eslint --fix --cache"],
"*.{json}": ["node scripts/validate-json.js"]
}
第三步,husky 钩子只留一行:
.husky/pre-commit
npx lint-staged --quiet
第四步,自定义脚本:
- lint-wxml.js 用 @wxml/parser 把文件 parse 成 AST,检查标签名、属性黑名单,非法就 process.exit(1);
- validate-json.js 用 page.schema.json 对 page.json 做校验,防止把 navigationStyle 写成 navigationstyle。
第五步,提速:
eslint/stylelint 加 --cache,缓存文件放到 node_modules/.cache,.gitignore 忽略;
大仓库再用 lint-staged 的 --concurrent 8,把耗时从 90s 压到 18s。
第六步,Windows 兼容:
所有 glob 用双引号,prettier 加 --end-of-line auto,避免 CRLF 报错。
上线半年,拦截了 300+ 次低质量提交,包括 wxs 里用了 ES6 模板字符串、page.json 缺失 component 字段等典型错误,团队回滚率下降 40%。”
拓展思考
- 如果仓库里同时有 Web 与小程序,两套 lint 规则冲突怎么办?
答:用 overrides 字段把规则拆成 “files: ['/*.wxml']” 和 “files: ['/*.vue']” 两段,或者给小程序单独建 .eslintrc.wxs.json,在 lint-staged 里通过 --config 指定。 - 未来微信官方把 wxml 升级成 wxml2,parser 不兼容怎么灰度?
答:在 lint-wxml.js 里先读 miniprogram.root 字段判断基础库版本,≥2.0 走新 parser,<2.0 走老 parser,实现平滑切换。 - 如何把同样的钩子下沉到脚手架,供 20 个业务线复用?
答:把 husky + lint-staged 配置抽成 @company/mp-lint 包,postinstall 阶段自动执行 husky install,业务线只依赖不感知,实现“一行 npm i 就带守门员”。