Как сделать сборник рассказов для поддержки локализации в проекте Gatsby?
Здесь я разрабатываю проект Gatsby, добавляя все разрабатываемые мной компоненты в сборник рассказов. я использую
gatsby-plugin-intl
для локализации. И я включил это в свои компоненты вот так.
Составная часть:
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { useIntl } from 'gatsby-plugin-intl';
import { isEmpty } from 'lodash';
import Typography from '../../../components/Typography';
import AddressContainer from './AddressContainer';
// import Button from '../../Button';
import './style.css';
const LocationInfoBox = ({ nearestLocationData, userLocationData }) => {
const intl = useIntl();
const [nearestLocations, setNearestLocations] = useState([]);
const [userLocation, setUserLocation] = useState({});
useEffect(() => {
setNearestLocations(nearestLocationData);
setUserLocation(userLocationData);
}, [nearestLocationData, userLocationData]);
return (
<>
{(!isEmpty(nearestLocations)) && (
<div className="location-info-card-container">
<div className="location-info-header-container">
<Typography component="p" className="location-info-header-text">
<span className="location-info-header-text-blue">{nearestLocations?.length}</span>
{' '}
<span className="location-info-header-text-normal">
{intl.formatMessage({ id: 'LocationsIn' })}{' '}{nearestLocations[0]?.provinceStateC?.split('-')[1]}
</span>
</Typography>
</div>
<div className="location-info-content-container" id="location-info-content-container-scrollBar">
{nearestLocations?.map((item, i) => (
<AddressContainer item={item} index={i} userLocation={userLocation} />
))}
</div>
</div>
)}
</>
);
};
LocationInfoBox.propTypes = {
nearestLocationData: PropTypes.array,
userLocationData: PropTypes.object,
};
export default LocationInfoBox;
Приведенный выше код отлично работает на сайте Gatsby. Но когда я добавляю это в сборник рассказов. Это вызывает ошибку, подобную этой
Error: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.
Вот как я создал Storybook для вышеуказанного компонента.
Сборник рассказов
import React from 'react';
import LocationInfoBox from './index';
import { userLocationData, nearestLocationData } from './data';
export default {
title: 'EFS/Molecules/LocationInfoBox',
component: LocationInfoBox,
};
const Template = (args) => {
return <LocationInfoBox {...args} />;
};
export const Default = Template.bind({});
Default.args = {
userLocationData,
nearestLocationData,
};
Ниже я делюсь своими конфигурациями сборника рассказов:
.storybook / main.js
const path = require('path');
module.exports = {
stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials',
'storybook-css-modules-preset',
],
webpackFinal: async (config, { configType }) => {
// `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
// You can change the configuration based on that.
// 'PRODUCTION' is used when building the static version of storybook.
// Make whatever fine-grained changes you need
config.module.rules.push({
test: /\.scss$/,
use: ['style-loader', 'css-loader?modules&importLoaders', 'sass-loader'],
include: path.resolve(__dirname, '../'),
});
// Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/];
// use installed babel-loader which is v8.0-beta (which is meant to work with @babel/core@7)
config.module.rules[0].use[0].loader = require.resolve('babel-loader');
// use @babel/preset-react for JSX and env (instead of staged presets)
config.module.rules[0].use[0].options.presets = [
require.resolve('@babel/preset-react'),
require.resolve('@babel/preset-env'),
];
config.module.rules[0].use[0].options.plugins = [
// use @babel/plugin-proposal-class-properties for class arrow functions
require.resolve('@babel/plugin-proposal-class-properties'),
// use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook
require.resolve('babel-plugin-remove-graphql-queries'),
];
// Prefer Gatsby ES6 entrypoint (module) over commonjs (main) entrypoint
config.resolve.mainFields = ['browser', 'module', 'main'];
// Return the altered config
return config;
},
};
.storybook / preview.js
import React from 'react';
import {
Title,
Subtitle,
Description,
Primary,
ArgsTable,
Stories,
PRIMARY_STORY,
} from '@storybook/addon-docs/blocks';
import { action } from '@storybook/addon-actions';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min';
import 'bootstrap-icons/font/bootstrap-icons.css';
import '../src/scss/custom.scss';
import '../src/fonts/fonts.css';
// Gatsby's Link overrides:
// Gatsby Link calls the `enqueue` & `hovering` methods on the global variable ___loader.
// This global object isn't set in storybook context, requiring you to override it to empty functions (no-op),
// so Gatsby Link doesn't throw any errors.
global.___loader = {
enqueue: () => {},
hovering: () => {},
}
// This global variable is prevents the "__BASE_PATH__ is not defined" error inside Storybook.
global.__BASE_PATH__ = '/';
// Navigating through a gatsby app using gatsby-link or any other gatsby component will use the `___navigate` method.
// In Storybook it makes more sense to log an action than doing an actual navigate. Checkout the actions addon docs for more info: https://github.com/storybookjs/storybook/tree/master/addons/actions.
window.___navigate = (pathname) => {
action('NavigateTo:')(pathname);
};
export const parameters = {
options: {
storySort: {
order: [
'EFS',
['Atoms', ['Foundation', 'Inputs'], 'Molecules', 'Organisms'],
],
},
},
layout: 'fullscreen',
docs: {
page: () => (
<>
<Title />
<Subtitle />
<Description />
<Primary />
<h2>Arguments</h2>
<ArgsTable story={PRIMARY_STORY} />
<Stories />
</>
),
},
backgrounds: {
default: 'default',
values: [
{
name: 'light-grey',
value: '#e7e7e7',
},
{
name: 'grey50',
value: '#f2f2f2',
},
{
name: 'grey25',
value: '#f8f8f8',
},
],
},
};
Нужно ли мне делать какие-либо конфигурации для поддержки intl в сборнике рассказов. Пожалуйста, помогите мне с этим.