参加直播:周四,美国东部时间上午 11 点,Storybook 9 发布和 AMA

源视图

Storybook 的源代码查看器插件

在 Github 上查看

Storybook 源视图插件

它是什么?

这是 Gauthier Fiorentino 最初的 Storybook-source-code-addon 的升级版本,适用于 Storybook。它允许浏览你的 Storybook 的任何人访问你组件的源代码。这个插件提供了一种传统库的替代方案,通过让用户直接复制粘贴你的代码而不是将其作为库来使用。

如何安装?

安装过程很简单

  • 首先,安装依赖
$ npm i -D @epicuristic/storybook-source-view
  • 然后将其添加到你的 .storybook/main.js
module.exports = {
  addons: ['@epicuristic/storybook-source-view']
}

入门

使用字符串

如果你的源代码存储为字符串,像这样添加到你的故事中

export default {
  title: 'Your story',
  parameters: {
    componentSource: {
      code: 'export default "This is my code"',
      language: 'javascript',
    }
  },
};

为了更好地组织,你可以将代码存储在单独的文件中

// MyComponent.code.js
export default `
const MyComponent = () => "Hello World"
`
import MyComponentCode from './MyComponent.code'

export default {
  title: 'Your story',
  parameters: {
    componentSource: {
      code: MyComponentCode,
      language: 'javascript',
    }
  },
};

使用 URL

如果你的仓库是公开可访问的,你可以向插件提供一个 URL

export default {
  title: 'Your story',
  parameters: {
    componentSource: {
      url: 'https://path.to.your.repository/file%2Etsx',
      language: 'javascript',
    }
  },
};

仓库常用的 API 模式包括

  • GitLab: https://gitlab.com/api/v4/projects/<ProjectID>/repository/files/<file path URL encoded>/raw?ref=master

多个文件

要公开多个文件,你可以使用一个 URL 数组

export default {
  title: 'Your story',
  parameters: {
    componentSource: {
      url: [
        'https://path.to.your.repository/file%2Etsx',
        'https://path.to.your.repository/file2%2Etsx',        
      ],
      language: 'javascript',
    }
  },
};

或者,如果你更喜欢使用代码字符串

export default {
  title: 'Your story',
  parameters: {
    componentSource: {
      code: [
        'export default "This is my code"',
        'export default "This is also my code"',
      ],
      language: 'javascript',
    }
  },
};