编写一个自定义 Autoprefixer 插件,为 `user-select: none` 添加 `-ms-user-select: element`
解读
- 面试官真正想考察的是“你能否用 PostCSS 插件机制精准地干预 CSS AST”,而不是让你去改 Autoprefixer 源码。
- 国内主流场景:Vue CLI / Vite / Webpack 默认已集成 PostCSS,业务线常需要“补刀”式兼容旧版 IE/Edge(
-ms-前缀)。 - 题目限定“仅当值为 none 时才追加
-ms-user-select: element”,要求逻辑严谨、无副作用,且必须返回新 AST,不能污染原节点。 - 性能与可维护性:插件需支持 PostCSS 8 插件 API(
Declaration事件 +Once生命周期),并给出 TypeScript 类型声明,方便后续接入公司 monorepo。
知识点
- PostCSS 插件结构:id、version、Once/Declaration 钩子、Rule/Declaration 节点模型
- 遍历与克隆:使用
decl.cloneBefore()保证源映射(source-map)连续 - 前缀策略:
-ms-user-select在 IE10-11 下对应值element而非none,需硬编码映射表 - 插件发布:package.json 中
peerDependencies声明postcss: ^8.2.0,避免多实例 - 测试用例:使用
postcss-plugin-tester做快照比对,CI 接入 GitHub Actions(国内可同步到 Gitee)
答案
// postcss-ms-user-select-none.ts
import { Plugin, Declaration } from 'postcss';
const plugin: Plugin = {
postcssPlugin: 'postcss-ms-user-select-none',
Once(root) {
root.walkDecls('user-select', (decl: Declaration) => {
if (decl.value === 'none') {
// 克隆并插入到原声明之前,保持顺序
decl.cloneBefore({
prop: '-ms-user-select',
value: 'element',
});
}
});
},
};
plugin.postcss = true;
export = plugin;
使用示例(postcss.config.js):
module.exports = {
plugins: [
require('./postcss-ms-user-select-none'),
require('autoprefixer'),
],
};
验证输入:
.foo {
user-select: none;
}
输出:
.foo {
-ms-user-select: element;
user-select: none;
}
拓展思考
- 如果需求升级为“对任意
user-select值都做完整前缀映射”,可维护一张浏览器数据表,结合 Can I Use 的 JSON 自动判断是否需要-ms-、-webkit-等,从而演化为轻量级“自定义 autoprefixer 内核”。 - 在微前端或低代码平台中,不同子应用可能引用不同 PostCSS 插件版本,需用
postcss-load-config的ctx.env区分构建环境,避免重复前缀。 - 对于 SSR 项目(Next.js、Nuxt),建议在
production环境下开启postcss-plugin的map: false选项,减少 source-map 体积,提升服务器打包速度。 - 国内合规要求:若项目需通过工信部备案检测,CSS 中不能出现
-webkit-touch-callout等被认定为“禁用长按菜单”的属性,此时可通过同一插件链路做后置扫描与告警,实现“兼容 + 合规”双保险。