加入直播会议:周四,东部时间上午 11 点,Storybook 9 版本发布与问答

一个 Storybook 插件,用于显示使用 Prismjs 高亮显示的任何类型的代码

在 Github 上查看

storybook-addon-code

React Storybook code addon

一个 Storybook 插件,可以在 Storybook 面板中为你的故事展示代码示例。

入门

npm i --save-dev storybook-addon-code

用法

在你的 storybook 配置中创建一个名为 addons.js 的文件。

添加以下内容

import * as CodeAddon from '../src/register';
CodeAddon.setTabs(
    [{ label: 'Sass', type: 'sass' }, {label: 'TypeScript', type: 'typescript'}]
);

setTab 函数接受一个对象,例如 {label: 'Sass', type:'sass'};或者如果你想拥有多个标签页,可以传递一个包含多个对象的数组。标签将显示在 Storybook 面板中。

然后像这样编写你的故事

import { storiesOf } from '@storybook/react';
import withCode from 'storybook-addon-code';
import Button from './Button';

const styleFile = require('raw-loader!./style.scss');
const typescriptFile  = require('./test.tsx');

storiesOf('Button', module)
  .addDecorator(withCode(typescriptFile, 'typescript'))
  .addDecorator(withCode(styleFile, 'sass'))
  .add('with text', () =>
      <Button onClick={action('clicked')}>Hello Button</Button>
    )

withCode 函数支持的格式列表

  1. clike (withCode(YourCFile, 'clike'))
  2. css (withCode(YourCssFile, 'css'))
  3. html (withCode(YourHtmlFile, 'html'))
  4. js | javascript (withCode(YourJavascriptFile, 'js'))
  5. markup (withCode(YourMarkupFile, 'js'))
  6. mathml (withCode(YourMatHmlFile, 'mathml'))
  7. sass (withCode(YourSassFile, 'sass'))
  8. svg (withCode(YourSvgFile, 'svg'))
  9. ts (withCode(YourTsFile, 'ts'))
  10. typescript (withCode(YourTypescriptFile, 'typescript'))
  11. xml (withCode(YourXmlFile, 'xml'))

查看这个示例故事,了解更多关于 withCode API 的信息