如何编译自定义焦点指示器样式

解读

面试官把“焦点指示器样式”和“Babel”放在一起问,并不是让你写一段 :focus-visible { outline: … } 的 CSS,而是考察你是否理解“编译链路如何把样式也纳入可编程、可移植、可降级”的工程体系。国内一线团队(阿里、字节、美团)在 2023 年以后普遍把“样式”当成源码的一部分,要求像 JS 一样做语法降级、按需打包、主题变量抽取、甚至做 Design Token 的静态分析。Babel 作为整个前端编译的“中枢”,需要回答三件事:

  1. 如何把“自定义焦点指示器”这种设计语义转成可配置的代码表达;
  2. 如何让它在低版本浏览器(IE11、Chrome 58)里自动降级;
  3. 如何保证按需打包,不因为一句 :focus-visible 就把 3 kB 的 polyfill 全部打进去。

因此,题目本质是“用 Babel 插件体系,把‘自定义焦点指示器’这条样式需求,编译成目标环境可运行、体积最小、可维护的代码”。

知识点

  1. AST 边界:CSS 本身不是 Babel 的 AST,但社区有 postcss-babel、@stylexjs/babel-plugin 等方案,把 CSS 转成 JS 对象或 TaggedTemplate,从而进入 Babel 的编译管道。
  2. 语法降级::focus-visible 在 Chrome 86+ 才支持,IE11 完全不识别;需要降级成 .focus-visible 类名 + JS 特征检测。
  3. 按需 polyfill:通过 @babel/helper-compilation-targets 读取 browserslist,如果 targets 已天然支持 :focus-visible,则插件直接擦除相关降级代码,实现“零运行时”。
  4. 静态抽取:利用 Babel 的 pre 和 post 钩子,把“主题色、圆角、outline-offset”等 Design Token 抽取成 CSS 变量或行内 style 对象,方便后续做主题切换和 Dark Mode。
  5. Tree-Shaking 友好:把“焦点指示器”封装成 focusVisible({ color, radius }) 这样的 JS 函数,Babel 编译时把未调用的分支直接删掉,避免空跑。
  6. SourceMap 回链:样式经过 JS 字符串拼接后,需要同时生成 *.css.map,保证浏览器 DevTools 里能定位回原始 JSX 或 Vue SFC 的行号,国内审计场景(金融、政务)强依赖这一点。

答案

下面给出一个可直接落地的 Babel 插件骨架,演示如何把“自定义焦点指示器”编译成目标环境可运行、零冗余、可配置的代码。假设源码里写的是:

import { focusVisible } from '@mylib/a11y';

const styles = focusVisible({
  color: '#1677ff',
  radius: 4,
  offset: 2
});

插件 babel-plugin-focus-visible 核心逻辑:

module.exports = function ({ types: t }) {
  return {
    name: 'focus-visible-custom',
    visitor: {
      ImportDeclaration(path, state) {
        const src = path.node.source.value;
        if (src !== '@mylib/a11y') return;

        const spec = path.node.specifiers.find(
          s => s.imported && s.imported.name === 'focusVisible'
        );
        if (!spec) return;

        // 记录本地变量名,后续 CallExpression 匹配用
        state.focusLocalId = spec.local.name;
      },

      CallExpression(path, state) {
        if (!state.focusLocalId) return;
        if (!path.get('callee').isIdentifier({ name: state.focusLocalId })) return;

        const arg = path.node.arguments[0];
        if (!t.isObjectExpression(arg)) return;

        // 1. 静态求值,拿到 color/radius/offset
        const opts = {};
        arg.properties.forEach(p => {
          if (t.isObjectProperty(p) && t.isStringLiteral(p.value)) {
            opts[p.key.name] = p.value.value;
          }
        });

        // 2. 读 browserslist,决定是否要降级
        const targets = state.opts.targets || require('@babel/helper-compilation-targets').default();
        const needPolyfill = !require('caniuse-lite').feature(
          require('caniuse-lite/data/features/focus-visible')
        ).stats[targets.ie];

        // 3. 生成降级代码或现代代码
        if (needPolyfill) {
          // 注入 focus-visible 类名补丁
          path.replaceWith(
            t.objectExpression([
              t.objectProperty(
                t.identifier('className'),
                t.stringLiteral(`focus-visible outline-custom`)
              ),
              t.objectProperty(
                t.identifier('style'),
                t.objectExpression([
                  t.objectProperty(
                    t.identifier('--focus-color'),
                    t.stringLiteral(opts.color)
                  ),
                  t.objectProperty(
                    t.identifier('--focus-radius'),
                    t.stringLiteral(String(opts.radius))
                  ),
                  t.objectProperty(
                    t.identifier('--focus-offset'),
                    t.stringLiteral(String(opts.offset))
                  )
                ])
              )
            ])
          );

          // 在全局作用域插入一次 polyfill 引用
          const program = path.getFunctionParent() || path.getStatementParent().getFunctionParent();
          if (program && !state.polyInserted) {
            program.unshiftContainer(
              'body',
              t.importDeclaration([], t.stringLiteral('focus-visible/dist/focus-visible.min.js'))
            );
            state.polyInserted = true;
          }
        } else {
          // 现代浏览器,直接输出 :focus-visible
          path.replaceWith(
            t.objectExpression([
              t.objectProperty(
                t.identifier('style'),
                t.objectExpression([
                  t.objectProperty(
                    t.identifier('outline'),
                    t.stringLiteral(`2px solid ${opts.color}`)
                  ),
                  t.objectProperty(
                    t.identifier('outlineOffset'),
                    t.stringLiteral(`${opts.offset}px`)
                  ),
                  t.objectProperty(
                    t.identifier('borderRadius'),
                    t.stringLiteral(`${opts.radius}px`)
                  )
                ])
              )
            ])
          );
        }
      }
    }
  };
};

配置 .babelrc.js:

module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { ie: '11' } }]
  ],
  plugins: [
    ['./babel-plugin-focus-visible', {
      targets: require('@babel/helper-compilation-targets').default()
    }]
  ]
};

运行后,IE11 产物里会自动:

  1. 引入 focus-visible.min.js(gzip 后 1.2 kB);
  2. 把 focusVisible({…}) 展开成 className="focus-visible outline-custom" + 行内 CSS 变量;
  3. 在支持的浏览器里直接输出 :focus-visible 的 style 对象,无额外运行时。

至此,“自定义焦点指示器样式”被 Babel 编译成了目标环境可运行、按需降级、体积最小、可维护的代码。

拓展思考

  1. 跨端场景:小程序基础库 2.30 以下不支持 :focus-visible,可以把插件再扩展一层,输出微信 hover-class 或支付宝 focus-class,实现“一处编写,三端降级”。
  2. Design Token 联动:把 color、radius 抽成全局 Token 文件,插件在 pre 阶段扫描所有 focusVisible 调用,生成 focus.css 并交给 Vite/Rspack 的 CSS 合并链路,实现“静态抽取 + 热更新”。
  3. 无障碍审计:国内金融合规要求“焦点可见对比度 ≥ 4.5:1”,插件可集成 wcag-contrast 检测,若 color 与背景色对比度不足,直接在 Babel 编译期抛 Error,阻断发版,左移无障碍风险。
  4. Monorepo 复用:把插件拆成 @company/babel-plugin-a11y,统一收敛所有“自定义焦点、自定义焦点环、高对比模式”的编译策略,避免各业务重复写 PostCSS 配置,契合国内大厂“基座工程”思路。