Storybook react-intl 擴充套件
在 Storybook 中新增 react-intl 支援。
所需版本
v3.1.x
- storybook -
^8.2.0
- react-intl -
^5.24.0 || ^6.0.0
v3.0.x
- storybook -
^8.0.0
- react-intl -
^5.24.0 || ^6.0.0
這個 Storybook 擴充套件假設您的專案已設定 react-intl,並且已正確配置且運作正常。
安裝
此擴充套件應作為開發依賴項加入。
npm i -D storybook-react-intl
yarn add -D storybook-react-intl
如果您的專案尚未安裝 react-intl
,您需要將其安裝為專案的依賴項。
npm i -S react-intl
yarn add react-intl
使用方法
安裝後,請按照以下步驟在 Storybook 中啟用此擴充套件。
main.ts
將此擴充套件插入您的 addons 陣列
{
addons: [
// other addons...
'storybook-react-intl',
]
}
reactIntl.ts
在您的 .storybook
資料夾中建立一個名為 reactIntl.ts
的檔案(或您喜歡的任何名稱)。您將在此處設定您的 react-intl 配置。
在此檔案中,複製並貼上以下程式碼,並進行您需要的任何修改。
const locales = ['en', 'de'];
const messages = locales.reduce((acc, lang) => ({
...acc,
[lang]: require(`../locale/${lang}.json`), // whatever the relative path to your messages json is
}), {});
const formats = {}; // optional, if you have any formats
export const reactIntl = {
defaultLocale: 'en',
locales,
messages,
formats,
};
preview.ts
在您的 preview.ts
中,您需要將 locales
和 locale
新增到 initialGlobals
(如果您未使用 storybook 8.2+,則為 globals
),並將您從上述檔案匯出的 reactIntl
新增到 parameters。
locales
是一個物件,其中鍵是 locales/語言的「id」,值是您想要在下拉選單中顯示的名稱。
locale
是預設的 locale,可以從 reactIntl
讀取,也可以根據您的選擇手動設定。
import {reactIntl} from './reactIntl';
const preview: Preview = {
initialGlobals: {
locale: reactIntl.defaultLocale,
locales: {
en: 'English',
de: 'Deutsche',
},
},
parameters: {
reactIntl,
}
};
export default preview;
您還可以將 locales 設定為與 Storybook 相容的物件,如 storybook-i18n 中所述(此擴充套件中包含此功能)。
import {reactIntl} from './reactIntl';
const preview: Preview = {
initialGlobals: {
locale: reactIntl.defaultLocale,
locales: {
en: {icon: '🇺🇸', title: 'English', right: 'EN'},
fr: {icon: '🇫🇷', title: 'Français', right: 'FR'},
ja: {icon: '🇯🇵', title: '日本語', right: 'JP'},
},
},
parameters: {
reactIntl,
}
};
export default preview;
Story 參數 Locale
如果您希望某個 story 使用特定的 locale,請將其設定在該 Story 的參數中。
export const Default: StoryObj = {
render: () => <YourComponent/>,
};
export const Japanese: StoryObj = {
parameters: {
locale: 'ja',
},
render: () => <YourComponent/>,
};
請注意,這樣做會將目前的 locale 切換到參數的 locale,因此當您變更到沒有參數的 story 時,它將停留在最後選取的 locale。
在上面的範例中,如果您檢視日文的 story,然後點擊回到預設的 story,則 locale 將保持 ja
。
完成這些步驟並啟動 storybook 後,您應該會在工具列中看到一個地球圖示。
點擊此地球圖示將會顯示一個下拉選單,其中包含您定義的 locales。
切換 locales 將會使用您的訊息中定義的字串。