You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何开发禁止styled-components硬编码样式的自定义stylelint插件

实现方案

1. 依赖安装

先安装开发自定义插件需要的基础依赖:

npm install stylelint postcss @stylelint/utils stylelint-processor-styled-components --save-dev

2. 插件目录结构

按照标准stylelint插件规范组织目录:

stylelint-plugin-styled-no-hardcode/
├── lib
│   └── rules
│       └── no-hardcoded-values.js # 规则核心实现
└── index.js # 插件入口

3. 核心代码实现

插件入口(index.js)

module.exports = {
  rules: {
    'no-hardcoded-values': require('./lib/rules/no-hardcoded-values'),
  },
};

规则实现(lib/rules/no-hardcoded-values.js)

const { utils } = require('stylelint');

const ruleName = 'styled-no-hardcode/no-hardcoded-values';
const messages = utils.ruleMessages(ruleName, {
  rejected: (prop, value) => `禁止在styled-components中硬编码样式值,属性${prop}的${value}请从公共设计常量文件引入`,
});

// 可配置的白名单,比如常用的0、auto、100%这类通用值允许直接使用
const defaultWhiteList = ['0', 'auto', '100%', '0%', '1px', 'inherit', 'initial', 'unset'];

module.exports = function(primaryOption, secondaryOptions = {}) {
  return function(root, result) {
    const validOptions = utils.validateOptions(result, ruleName, {
      actual: primaryOption,
      possible: [true],
    }, {
      actual: secondaryOptions,
      possible: {
        whiteList: [Array],
      },
      optional: true,
    });
    if (!validOptions) return;

    const whiteList = [...defaultWhiteList, ...(secondaryOptions.whiteList || [])];
    // 匹配硬编码的颜色、长度单位值的正则
    const hardcodeReg = /(^#[0-9a-fA-F]{3,8}$)|(^rgba?\(.+\)$)|(^hsla?\(.+\)$)|(^[0-9.]+(px|rem|em|vw|vh|%|pt|pc)$)|(^[a-z]+$)/i;

    root.walkDecls(decl => {
      const value = decl.value.trim();
      // 跳过白名单值
      if (whiteList.includes(value)) return;
      // 跳过styled-components插值生成的占位符(processor会把${xxx}替换为$sc-placeholder开头的占位值)
      if (value.startsWith('$sc-')) return;
      // 匹配到硬编码值就上报错误
      if (hardcodeReg.test(value)) {
        utils.report({
          message: messages.rejected(decl.prop, value),
          node: decl,
          result,
          ruleName,
        });
      }
    });
  };
};

module.exports.ruleName = ruleName;
module.exports.messages = messages;

4. 项目接入配置

在需要使用该插件的项目中,修改stylelint.config.js配置:

module.exports = {
  // 注册styled-components处理器,自动解析模板字符串里的样式
  processors: ['stylelint-processor-styled-components'],
  // 注册自定义插件
  plugins: ['stylelint-plugin-styled-no-hardcode'],
  rules: {
    // 开启自定义规则,也可以自定义白名单
    'styled-no-hardcode/no-hardcoded-values': [true, {
      whiteList: ['none', 'transparent']
    }],
  },
  // 配置需要校验的文件后缀
  overrides: [
    {
      files: ['**/*.jsx', '**/*.tsx'],
      customSyntax: '@stylelint/postcss-css-in-js',
    },
  ],
};

5. 校验效果匹配

  • 错误写法会触发报错:
    const Header = styled.div`
      font-size: 14px; // 触发报错
      color: red; // 触发报错
    `;
    
  • 正确写法不会触发报错:
    import {FONT, COLOR} from 'constants';
    
    const Header = styled.div`
      font-size: ${FONT.M};
      color: ${COLOR.PRIMARY};
    `;
    

内容的提问来源于stack exchange,提问作者Anirudh Modi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:06:02