Storybook react-intl 插件
为 Storybook 添加 react-intl 支持。
所需版本
v4.x
- storybook -
^9.0.0
- react-intl -
^5.24.0 || ^6.0.0
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,
timeZone: 'America/New_York', // optional, specify a time zone
};
preview.ts
在你的 preview.ts
中,你需要将 locales
和 locale
添加到 initialGlobals
(如果你未使用 storybook 8.2+,则为 globals
),并将你从上述文件导出的 reactIntl
添加到 parameters 中。
locales
是一个对象,其键是 locale/语言的“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;
故事参数 Locale
如果你希望故事使用特定的 locale,可以在该故事的参数中设置它。
export const Default: StoryObj = {
render: () => <YourComponent/>,
};
export const Japanese: StoryObj = {
parameters: {
locale: 'ja',
},
render: () => <YourComponent/>,
};
请注意,这样做会将当前 locale 切换到参数指定的 locale,因此当你切换到没有参数的故事时,locale 会保持在上次选定的状态。
在上面的例子中,如果你查看了日文故事,然后点击返回默认故事,locale 仍将保持为 ja
。
完成这些步骤并启动 storybook 后,你应该在工具栏中看到一个地球图标。
点击此地球图标将显示一个包含你定义的 locales 的下拉列表。
切换 locales 将使用你在 messages 中定义的字符串。