如何检测 @import 出现在非首行?

解读

国内前端团队普遍采用 Stylelint 做“门禁”级卡点,CI 流水线一旦检测到不合规代码即拒绝合并。
@import 必须放在样式文件最顶部是《阿里巴巴前端规约》《腾讯 CSS 编写规范》等国内大厂文档的硬性条款,理由有三:

  1. 浏览器遇到 @import 会阻塞渲染,后置会造成重复回流;
  2. webpack、Vite 等构建工具对“首行 @import”可做依赖图优化,后置会退化为运行时加载;
  3. 代码可读性:所有依赖前置,后续只关注样式实现。
    因此“如何检测 @import 不在首行”是面试官高频追问的“规范落地”题,既考察对 Stylelint 规则体系的熟悉度,也考察 AST 定位思路与自定义规则能力。

知识点

  1. PostCSS AST 节点类型:AtRule.name === 'import'
  2. 规则编写骨架:
    • ruleName 必须带命名空间(如 plugin/import-not-first)
    • create 函数返回 { AtRule(node, { report, ruleName, result }) { ... } }
  3. 首行判定:
    • 文件第一个非注释、非空、非 @charset 的 Token 即为“首行”
    • 通过 node.source.start.line 与第一个有效 Token 的行号比较
  4. 自动修复:
    • 在 AtRule 节点上调用 fix 回调,将 node.raws.before 置为空字符串,再调用 node.moveTo(root, root.first)
  5. 国内工程化配套:
    • 规则需发布到私有 npm(如 @company/stylelint-plugin)
    • 在 .stylelintrc.js 中 extends 数组里引入,配合 husky + lint-staged 在 commit-msg 阶段拦截

答案

给出一份可直接落地的自定义规则源码,并演示配置与运行效果。

  1. 新建规则文件 src/rules/import-not-first.js
const stylelint = require('stylelint');
const { utils } = stylelint;
const ruleName = 'plugin/import-not-first';
const messages = utils.ruleMessages(ruleName, {
  expected: '@import must appear at the first non-comment line',
});

function rule(primary, _, context) {
  return (root, result) => {
    const validOptions = utils.validateOptions(result, ruleName, {
      actual: primary,
      possible: [true],
    });
    if (!validOptions) return;

    let firstEffectiveLine = null;
    // 找到第一个有效 Token 的行号
    root.walk(node => {
      if (node.type === 'comment') return;
      if (node.type === 'atrule' && node.name === 'charset') return;
      if (firstEffectiveLine === null) {
        firstEffectiveLine = node.source.start.line;
      }
    });

    root.walkAtRules('import', atRule => {
      if (atRule.source.start.line !== firstEffectiveLine) {
        if (context.fix) {
          // 自动修复:剪切到顶部
          atRule.raws.before = '';
          root.prepend(atRule);
        } else {
          utils.report({
            message: messages.expected,
            node: atRule,
            result,
            ruleName,
          });
        }
      }
    });
  };
}

rule.ruleName = ruleName;
rule.messages = messages;
module.exports = stylelint.createPlugin(ruleName, rule);
  1. 注册插件
// .stylelintrc.js
module.exports = {
  plugins: ['./src/rules/import-not-first'],
  rules: {
    'plugin/import-not-first': [true, { severity: 'error' }],
  },
};
  1. 运行
npx stylelint "src/**/*.{css,scss}"

若检测到 @import 不在首行,终端输出:
src/index.css:7:1 ✖ @import must appear at the first non-comment line plugin/import-not-first
加 --fix 可自动剪切到顶部并格式化。

拓展思考

  1. 性能优化:
    在 monorepo 场景下,可把 firstEffectiveLine 缓存到 WeakMap,避免重复遍历 AST。
  2. 兼容 Less:
    Less 允许变量定义在 @import 之前,需把“变量声明”也视为有效 Token,可扩展 walk 逻辑识别 @variable。
  3. 与官方规则组合:
    配合 stylelint-config-standard 的 import-notation 与 no-duplicate-at-import-rules,形成“依赖前置 + 写法统一 + 去重”三位一体规范。
  4. 发布与灰度:
    国内大厂通常将自定义规则打入 eslint-config-company 同级的 stylelint-config-company,在 CI 中按项目维度灰度,逐步把 legacy 代码纳入白名单,避免一次全量爆红阻塞迭代。