是否可以在开发过程中实时重新加载 react-intl 消息

Is it possible to live reload react-intl messages during development

是否可以在开发过程中实时重新加载 react-intl 消息(对于默认语言)?

我的意思是像热模块加载一样,只有更新的消息会受到影响。任何没有 运行 额外脚本或刷新整个页面的其他解决方案也可以。

谢谢。

您可以 module.hot.accept 您的 翻译 消息并将其呈现为参数。请参阅 react-boilerplate

中的示例

https://github.com/react-boilerplate/react-boilerplate/blob/v3.5.0/app/app.js

const render = (messages) => {
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={messages}>
        <ConnectedRouter history={history}>
          <App />
        </ConnectedRouter>
      </LanguageProvider>
    </Provider>,
    MOUNT_NODE
  );
};

if (module.hot) {
  // Hot reloadable React components and translation json files
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept(['./i18n', 'containers/App'], () => {
    ReactDOM.unmountComponentAtNode(MOUNT_NODE);
    render(translationMessages);
  });
}

以防万一有人需要,我为此写了HOC;

import React, {Component} from "react";
import {IntlProvider} from "react-intl";

const url = location.protocol + '//' + location.host + "/";

class IntlLoader extends Component {
    constructor(props) {
        super(props);
        const {initialLocale: locale, initialMessages: messages} = props;
        this.state = {locale: 'en', messages};
    }

    fetchLanguagesForDevelopment = () => {
        // if development, use hot loading
        if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
            this.setState({...this.state, loading: true})
            fetch(url + "reactIntlMessages.json")
                .then((res) => {
                    return res.json();
                })
                .then((messages) => {
                    this.setState({loading: false})
                    if (messages !== this.state.messages)
                        this.setState({...this.state, messages})
                })
                .catch((error) => {
                    this.setState({error, loading: false})
                })
        } else {
            const messages = require('../../dist/reactIntlMessages.json')
            if (this.state.messages !== messages)
                this.setState({...this.state, messages, loading: false})
        }
    }

    componentDidMount() {
        this.fetchLanguagesForDevelopment()
    }


    componentWillReceiveProps(nextProps) {
        this.fetchLanguagesForDevelopment()
    }

    render() {
        const {error, messages, loading} = this.state;
        //if (loading) return (<div>Please wait...</div>)
        if (error) return (<div>Error While Loading Language</div>)

        return (
            <IntlProvider {...this.state}>
                {this.props.children}
            </IntlProvider>
        );
    }
}

export default IntlLoader