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
是一个对象,其中键是 locales/languages 的“id”,值是您希望在下拉列表中显示的名称。
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 参数中的区域设置
如果您想让某个 story 使用特定的区域设置,请在该 Story 的参数中设置它。
export const Default: StoryObj = {
render: () => <YourComponent/>,
};
export const Japanese: StoryObj = {
parameters: {
locale: 'ja',
},
render: () => <YourComponent/>,
};
请注意,这样做会将当前区域设置切换到参数指定的区域设置,因此当您切换到没有参数的 story 时,它将停留在上次选择的区域设置。
在上面的示例中,如果您查看日语 story,然后点击返回默认 story,区域设置将保持为 ja
。
完成这些步骤并启动 Storybook 后,您应该会在工具栏中看到一个地球图标。
点击此地球图标将显示一个下拉列表,其中包含您定义的区域设置。
切换区域设置将使用您在消息中定义的字符串。