@storybook/addon-themes
執行以下腳本來安裝並註冊外掛
npx storybook@latest add @storybook/addon-themes
這將執行一個設定腳本,引導您設定外掛。當出現提示時,從設定選項中選擇 styled-components
。
在幕後,這會執行 npx @storybook/auto-config themes
,它應該會讀取您的專案並嘗試使用正確的裝飾器設定您的 Storybook。如果直接執行該命令沒有解決您的問題,請在 @storybook/auto-config 儲存庫上提交錯誤報告,以便我們進一步改進它。要手動新增此外掛,請安裝它,然後將它新增到您 .storybook/main.ts
中的 addons 陣列。
GlobalStyles
在 .storybook/preview.js
中,建立一個包含 font-family
的 <GlobalStyles />
元件。然後使用 withThemeFromJSXProvider
裝飾器將其應用於您的 stories,方法是將其新增到 decorators
陣列中。
// .storybook/preview.jsx
import { withThemeFromJSXProvider } from '@storybook/addon-themes';
import { createGlobalStyle } from 'styled-components';
const GlobalStyles = createGlobalStyle`
body {
font-family: "Nunito Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
`;
export const decorators = [
withThemeFromJSXProvider({
GlobalStyles, // Adds your GlobalStyle component to all stories
}),
];
如果您的應用程式中已存在 <GlobalStyles />
,您可以將其匯入到 .storybook/preview.js
中,而不是重新建立它。
要與 Storybook 中的元件分享您的主題,您需要將它們與 styled-components
<ThemeProvider />
元件一起提供給 withThemeFromJSXProvider
裝飾器。
// .storybook/preview.jsx
import { createGlobalStyle, ThemeProvider } from 'styled-components';
import { withThemeFromJSXProvider } from '@storybook/addon-themes';
import { lightTheme, darkTheme } from '../src/themes';
/* snipped for brevity */
export const decorators = [
withThemeFromJSXProvider({
themes: {
light: lightTheme,
dark: darkTheme,
}
defaultTheme: 'light',
Provider: ThemeProvider,
GlobalStyles,
})];
當您提供多個主題時,Storybook UI 中將會出現一個工具列選單,以選擇您想要的 stories 主題。
現在您可以使用 styled-components 和 Storybook 了。🎉
如果您在工作中使用 styled-components,我們很樂意您協助使此設定更容易。加入 Discord 中的維護者以參與貢獻,或跳到外掛文件。