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

如何用函数抽象Storybook的CSF默认导出对象?

问题

我想为Storybook抽象CSF默认导出对象,写了以下代码:

metaFunction.js

export const getMeta = (title, component) => ({
  title: `Example/${title}`,
  component: component,
  tags: ['autodocs'],
  argTypes: {
    backgroundColor: { control: 'color' },
  },
});

Button.stories.js:

import { Button } from './Button';
import { getMeta } from './metaFunction';

// 此写法可行👇
// const meta = {
//   title: 'Example/Button',
//   component: Button,
//   tags: ['autodocs'],
//   argTypes: {
//     backgroundColor: { control: 'color' },
//   },
// };

// 此写法报错👇
const meta = getMeta('Button', Button);

export default meta;

export const Primary = {
  args: {
    primary: true,
    label: 'Button',
  },
};

export const Secondary = {
  args: {
    label: 'Button',
  },
};

export const Large = {
  args: {
    size: 'large',
    label: 'Button',
  },
};

export const Small = {
  args: {
    size: 'small',
    label: 'Button',
  },
};

直接声明对象的写法正常,但用getMeta函数生成meta时,Storybook会崩溃并抛出错误“CSF: missing default export”,请问有没有办法通过函数抽象CSF默认导出对象?

复现步骤:

  • 拉取仓库的function_debug分支
  • 执行npm install
  • 运行npm run storybook

解决方案

方法1:用Storybook官方定义函数包裹返回值

Storybook提供了专门的函数帮助静态分析识别meta对象,比如defineMeta(不同框架包名略有差异,比如React对应@storybook/react)。修改metaFunction.js:

// metaFunction.js
import { defineMeta } from '@storybook/react';

export const getMeta = (title, component) => defineMeta({
  title: `Example/${title}`,
  component: component,
  tags: ['autodocs'],
  argTypes: {
    backgroundColor: { control: 'color' },
  },
});

这样静态分析工具能正确识别导出的meta结构,不会报错。

方法2:让函数返回值可被静态分析

把固定配置抽成常量再合并动态参数,降低静态分析的识别难度:

// metaFunction.js
const BASE_META = {
  tags: ['autodocs'],
  argTypes: {
    backgroundColor: { control: 'color' },
  },
};

export const getMeta = (title, component) => ({
  ...BASE_META,
  title: `Example/${title}`,
  component: component,
});

方法3:直接在export default中调用函数

部分Storybook版本支持跳过变量赋值,直接把函数调用结果作为默认导出:

// Button.stories.js
import { Button } from './Button';
import { getMeta } from './metaFunction';

export default getMeta('Button', Button);

// 其余stories代码保持不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:20:00