如何校验 :host 选择器必须设置 display 属性?

解读

面试官抛出这道题,核心想验证三件事:

  1. 你是否真的写过 Web Components,知道 :host 的渲染特殊性;
  2. 能否把“业务约束”翻译成“静态规则”,体现你对 Stylelint 插件机制的深度理解;
  3. 是否具备把规则贡献给团队基建、落地到 CI 的闭环思维。
    国内大厂目前普遍把 Web Components 用在微前端子应用、跨技术栈组件库、低代码平台,:host 没写 display 会导致外层影子节点布局塌陷,属于“看起来能跑,一上线就炸”的典型故障。因此这道题不是考语法,而是考“如何不让队友掉坑”的工程化能力。

知识点

  1. :host 选择器语义
    仅存在于 Shadow DOM 内,匹配影子根宿主元素;浏览器默认 display: inline,一旦内部组件是块级布局,宿主却保持 inline,就会出现不可预料的换行或尺寸计算错误。
  2. Stylelint 规则运行原理
    基于 PostCSS AST,每条规则都是一个函数,接收 root 与 result 两个对象,通过 walkRules / walkDecls 遍历节点,用 report() 上报错误。
  3. 自定义规则包目录规范
    国内团队通常把私有规则放在 @company/stylelint-config-webcomponents 包内,lib/rules 下放规则实现,index.js 统一导出,__tests__ 写用例,保证后续可同步到 GitHub Actions 做门禁。
  4. 自动修复逻辑
    若缺失 display,可默认补 display: block; 但需允许用户通过 secondaryOptions 自定义值,避免“一刀切”破坏行内场景。
  5. 与已有规则冲突规避
    需要声明 meta.url 与 meta.fixable,并在插件文档里提示“若已启用 property-required-list,请关闭对应冲突字段”。

答案

给出“能直接落地”的最小可用方案,分三步:

  1. 新建规则文件 lib/rules/host-display-required.js
const { utils } = require('stylelint');

const ruleName = 'wc/host-display-required';
const messages = utils.ruleMessages(ruleName, {
  expected: 'The :host selector must declare a "display" property',
});

const meta = {
  url: 'https://github.com/company/stylelint-config-webcomponents/blob/main/lib/rules/host-display-required.js',
  fixable: true,
};

function rule(primary, secondaryOptions) {
  return (root, result) => {
    const validOptions = utils.validateOptions(
      result,
      ruleName,
      { actual: primary },
      {
        actual: secondaryOptions,
        possible: {
          displayValue: ['block', 'inline-block', 'flex', 'inline-flex'],
        },
        optional: true,
      }
    );
    if (!validOptions) return;

    const displayValue = secondaryOptions?.displayValue || 'block';

    root.walkRules(/:host(\([^)]*\))?$/i, (ruleNode) => {
      let hasDisplay = false;
      ruleNode.walkDecls('display', () => {
        hasDisplay = true;
      });
      if (hasDisplay) return;

      // 上报错误
      utils.report({
        message: messages.expected,
        node: ruleNode,
        result,
        ruleName,
        fix(fixer) {
          const lastDecl = ruleNode.last;
          const semicolon = lastDecl && lastDecl.type === 'decl' ? '' : ';';
          const indent = ruleNode.source.start.column;
          const spaces = ' '.repeat(indent);
          return fixer.insertAfter(
            lastDecl || ruleNode,
            `\n${spaces}display: ${displayValue};`
          );
        },
      });
    });
  };
}

rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = meta;

module.exports = rule;
  1. 在插件包入口导出
// index.js
module.exports = [
  require('./lib/rules/host-display-required'),
];
  1. 业务侧使用
    .stylelintrc.js
module.exports = {
  plugins: ['@company/stylelint-config-webcomponents'],
  rules: {
    'wc/host-display-required': [true, { displayValue: 'block' }],
  },
};

至此,本地 npx stylelint "**/*.css" 即可报错并一键修复;CI 里加 --max-warnings 0 即可拦截合并请求。

拓展思考

  1. 规则粒度拆分
    如果团队同时要求 :host 必须写 display 且禁止写 display: contents(因为会导致无障碍树丢失),可以把“必须”和“禁止”拆成两条规则,方便按需组合。
  2. 与 Design Token 结合
    把 displayValue 默认指向 @tokens/host-display 变量,规则里判断 decl.value.includes('@tokens/host-display') 也算通过,可强制走设计系统收口。
  3. 性能优化
    在 Monorepo 场景下,扫描 5000+ 文件时可通过 result.stylelintType === 'css-in-js' 提前跳过非 Shadow 样式,降低 30% 耗时。
  4. 贡献回社区
    把规则提 PR 给 stylelint-ecosystem 组织,让 Web Components 规则成为官方子集,提升国内开发者在国际社区的话语权。