概念
Storybook 的裝飾器非常強大,但伴隨著強大力量而來的是巨大的責任。
一開始定義全域裝飾器是沒問題的。但隨著專案的成長,不同的路徑可能需要不同的管理或裝飾器。
將這些裝飾器添加到每個 story 中,從維護的角度來看是無法擴展的。
那麼,**在資料夾層級定義裝飾器** 呢?
設定
透過新增 storybook-include
依賴項來安裝此擴充功能
yarn add -D storybook-include
在 .storybook/main.js 中
module.exports = {
addons: [
'storybook-include',
// or
require.resolve('storybook-include/preset'),
],
};
使用方式
-
不需要對 stories 進行任何變更,一切都可以外部設定
-
在資料夾中建立一個
storybook.include.js
、.ts
或.jsx/.tsx
。它可以是任何資料夾,包括您的 home 資料夾 -
設定要包含哪些裝飾器
-
它運作了
設定
範例檔案
// storybook.include.js
import { addStoryDecorators } from 'storybook-include';
// decorators are defined via default export
export default () => {
addStoryDecorators((story, { storyName, fileName }) => {
// you can mutate story
story.args = { decorated: true };
// you can add decorators
story.decorators.push(myDecorator);
// you can return an array of decorators to add
return storyName.includes('dark') ? [darkModeDecorator] : undefined;
});
// another set
addStoryDecorators((story, { fileName }) => {
return fileName.includes('page') ? [ReactRouterDecorator, StaticRouterDecorator] : undefined;
});
// another set
addStoryDecorators((story) => {
return [CSSInJS, Theme, AndSomethingElse];
});
};
重複使用設定
在少數情況下,您可能會考慮在兩個設定檔案之間共享相同的設定。雖然簡單的重複通常是首選,但有一種更簡單的方法可以做到
// storybook.include
import another from '../../other/storybook.include';
// ^ it's from another "branch", all explit parents will be "included" in any case
export default () => {
// do you thing
another();
};
用於非 .stories.*
檔案
有時,可能會使用非標準的 story 檔案名稱 - .story.*
、example.*
等。在這種情況下,預設預設值將不起作用,並且需要自訂一個
// your custom preset
/* eslint-disable no-param-reassign */
export function babel(options) {
options.overrides = options.overrides || [];
options.overrides.push({
test: /\.stories\.tsx?/, // <-- pattern matching your stories
plugins: [require.resolve('storybook-include/babel')],
});
return options;
}
關於快取的注意事項
雖然 Storybook 沒有強制執行建置快取,但此外掛程式的建置考慮到了這一點。因此,每個檔案都會自動設定其上方的所有「include 檔案」,而其他每個檔案都可以「重新設定」該清單。
理論上,這會影響未快取系統的效能。
⛔️ 移除或重新命名include 檔案可能需要更新快取。
另請參閱
- storybook-csf-title - 一個語義接近的外掛程式 - 根據 story 檔案的位置為 Storybook 建立
title
。
授權
MIT