Storybook 程式碼擴充套件
這個 Storybook 擴充套件可讓您顯示元件的原始碼。它使用 highlight.js 進行語法高亮顯示。可用的語言在此列出。
注意:此擴充套件只能與 Storybook 5.2 中引入的新的元件故事格式 (CSF) 一起使用。
開始使用
npm i --save-dev @whitespace/storybook-addon-code
註冊擴充套件
在您的 storybook 設定中建立一個名為 addons.js
的檔案,並新增以下內容
import registerAddonCode from '@whitespace/storybook-addon-code/register';
registerAddonCode({
tabs: [
{ label: 'Twig', lang: 'twig' },
{ label: 'Sass', lang: 'scss' },
{ label: 'JavaScript', lang: 'javascript', matchFiles: 'js' },
],
});
tabs
應該是一個陣列,其中包含您要新增到擴充套件面板的每個索引標籤的物件。每個物件可以包含以下屬性
label
:索引標籤上顯示的標籤。lang
:由 highlight.js 定義的語言。可用的語言在此列出matchFiles
:選用。預設值與lang
相同。可以是表示應包含的檔案的檔案副檔名的字串。也可以是用於測試檔案名稱的正規表示式。也可以是接收檔案名稱並傳回 true 或 false 的函式。
新增 Webpack 載入器
在您的 .storybook
目錄內更新或建立 webpack.config.js
,方法是將 require.resolve('@whitespace/storybook-addon-code/loader')
作為預先載入器新增至 .stories.js
檔案,如下所示。
module.exports = async ({ config, mode }) => {
// ...
config.module.rules.push({
test: /\.stories\.jsx?$/,
loaders: [
/*
This loader should be first in the list unless you
want tranfromations from other loaders to affect
what’s shown in the code tabs
*/
require.resolve('@whitespace/storybook-addon-code/loader'),
// ...
],
enforce: 'pre',
});
// ...
// Return the altered config
return config;
};
用法
會自動提取 .stories.js
檔案中符合已註冊索引標籤的匯入檔案。安裝並使用 null-loader 來包含實際故事檔案不需要的檔案。
import Component from './button.twig';
import '!!null-loader!./button.scss';
export default {
title: 'Example button',
};
export const withUrl = () =>
Component({
text: 'Lorem ipsum',
url: '#',
});
export const withoutUrl = () =>
Component({
text: 'Lorem ipsum',
});