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

如何在CI流水线中强制组件配Storybook Story并实现合规检测?

检查组件是否附带Storybook Story的可行方案

一、自定义Node.js脚本检查

这是适配性最强的方案,可根据你的项目目录结构灵活调整:

  • 核心逻辑:遍历组件目录,对每个组件文件,检查同目录或指定路径下是否存在匹配命名规则的Story文件(比如[组件名].stories.tsx/.jsx)
  • 示例脚本:
const fs = require('fs');
const path = require('path');

// 替换为你的组件根目录
const componentsDir = path.resolve(__dirname, './src/components');

function checkMissingStories(dir) {
  const files = fs.readdirSync(dir);
  const missing = [];

  files.forEach(file => {
    const fullPath = path.join(dir, file);
    const stat = fs.statSync(fullPath);

    if (stat.isDirectory()) {
      checkMissingStories(fullPath);
      return;
    }

    // 过滤组件文件,排除Story文件本身
    if (file.match(/\.(tsx|jsx)$/) && !file.includes('.stories.')) {
      const componentName = file.replace(/\.(tsx|jsx)$/, '');
      const storyPath = path.join(dir, `${componentName}.stories.tsx`);
      if (!fs.existsSync(storyPath)) {
        missing.push(fullPath);
      }
    }
  });

  if (missing.length > 0) {
    console.error('以下组件缺少对应的Storybook Story:');
    missing.forEach(item => console.error(`- ${item}`));
    process.exit(1); // 返回非0状态码,终止CI流水线
  } else {
    console.log('所有组件均已配置对应的Storybook Story');
  }
}

checkMissingStories(componentsDir);
  • CI集成:在GitHub Actions、GitLab CI等配置中添加步骤,运行该脚本,脚本失败时直接终止流水线。

二、解析Storybook构建元数据检查

利用Storybook自身生成的元数据做对比:

  • 实现步骤:
    1. 运行storybook build生成静态产物,其中storybook-static目录下会包含stories.json,记录所有已注册的Story信息
    2. 编写脚本读取stories.json中的组件列表,再遍历项目组件目录,找出未被收录的组件
  • 优势:无需依赖文件命名规则,直接基于Storybook实际注册的组件做校验

三、自定义ESLint规则

如果项目已使用ESLint,可以扩展规则实现实时检查:

  • 示例规则简化版:
module.exports = {
  rules: {
    'component-requires-story': {
      create(context) {
        const filename = context.getFilename();
        // 仅针对组件目录下的文件检查
        if (!filename.includes('/src/components/') || !filename.match(/\.(tsx|jsx)$/)) {
          return {};
        }

        const storyPath = filename.replace(/\.(tsx|jsx)$/, '.stories.tsx');
        if (!fs.existsSync(storyPath)) {
          context.report({
            node: context.getSourceCode().ast,
            message: '该组件必须附带对应的Storybook Story文件'
          });
        }
        return {};
      }
    }
  }
};
  • 使用方式:将规则加入ESLint配置,在CI中运行eslint --ext .tsx,.jsx src/components,让违规项触发流水线失败

四、Git钩子前置拦截(可选)

用Husky等工具在代码提交前运行上述脚本或ESLint规则,提前拦截不符合要求的提交,减少CI阶段的无效运行


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:30:56