npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-intl-modules-loader

v2.0.0

Published

A more scalable way of defining react-intl messages.

Downloads

11

Readme

react-intl-modules-loader is a webpack loader which allows you to structure your react-intl localisation files in a modular fashion.

The idea is that you keep your intl messages as close as possible to the component that uses them, which allows you to move your code around. It also means that it's easier to track which messages are used by which parts of the code - if you remove a file that's being used, Webpack will give you an error.

Let's say you have an components/ActionButtons directory with this file inside:

    // src/components/ActionButtons/intl.json
    {
        "en": {
            "save": {
                "default": "Save",
                "busy": "Saving…",
                "retry": "Retry"
            },
            "send": {
                "default": "Send",
                "busy": "Sending…",
                "retry": "Retry"
            }
        }
    }

When you require it via Webpack you will get a set of unique message IDs, something like:

    {
        "save": {
            "default": "components/ActionButtons/intl.json:save.default",
            "busy": "components/ActionButtons/intl.json:save.busy",
            "retry": "components/ActionButtons/intl.json:save.retry"
        },
        "send": {
            "default": "components/ActionButtons/intl.json:send.default",
            "busy": "components/ActionButtons/intl.json:send.busy",
            "retry": "components/ActionButtons/intl.json:send.retry"
        }
    }

Structure

Notice how the structure of the JSON is preserved.

You can shorten the module prefixes by setting shorten to true in the loader options, but this will make the loader non-deterministic because the shortened prefixes will depend on the order in which the modules are loaded.

Here's a React component that uses this to create a set of localised action buttons.

    // src/components/ActionButtons/index.js
    import React from "react";
    import {FormattedMessage} from "react-intl";
    import * as messages from "./intl.json";
    
    export class ActionButton extends React.Component {
        static propTypes = {
            onClick: React.PropTypes.func,
            busy: React.PropTypes.bool,
            error: React.PropTypes.string,
            ids: React.PropTypes.object
        };
        
        getID() {
            if (this.props.busy)
                return this.props.ids.busy;
            if (this.props.error)
                return this.props.ids.retry;
            return this.props.ids.default;
        }
        
        render() {
            return (
                <button onClick={this.props.onClick}
                        disabled={this.props.busy}
                        title={this.props.error}>
                    <FormattedMessage id={this.getID()}/>
                </button>;
            );
        }
    }
    
    export const SaveButton = (props) => 
        <ActionButton {...props} ids={messages.save}/>
        
    export const SendButton = (props) => 
        <ActionButton {...props} ids={messages.send}/>

Of course, this isn't useful to you unless you have a dictionary of messages to pass to IntlProvider. That's where require.context comes in handy. At the root of your project, you can use require.context and the combine helper to combine all your intl modules into one:

    // src/IntlProvider.js
    import combine from "react-intl-modules-loader/combine";
    import {IntlProvider} from "react-intl";
    
    const locales = combine(
        // Require all intl.json files in the project, take the messages from each, 
        // and combine them into a single dictionary of messages.
        require.context(
            "./",
            true, // Recurse into subdirectories
            /intl\.json$/)); // Or whatever you want to call your intl files.
    };
    
    export default (props) => 
        <IntlProvider messages={locales[props.lang] || locales.en}>
            {props.children}
        </IntlProvider>;

Suggested configuration

To load JSON files, you could put this into your Webpack 2 module.rules:

            {
                test: /^intl\.json$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "react-intl-modules-loader"
                    },
                    {
                        loader: "json-loader"
                    }
                ]
            },

To load plain JavaScript i18n files, you could put this into your module.rules:

            {
                test: /^intl\.js$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "react-intl-modules-loader"
                    }
                ]
            },

Loading non-JSON i18n files

In the spirit of Webpack, this loader does as little as possible. Originally, it parsed the JSON file for you. Now, that is optional, and can be done by chaining with json-loader. This allows for more complex scenarios such as sharing strings between components, and comments in your i18n files.

    // src/components/intl.js (global/common i18n strings)
    export const en = {
        retry: "Retry"
    };
    // src/components/Widget/intl.js
    import * as Global from "../intl.js";

    export const en = {
        save: {
            default: "Save",
            busy: "Saving…",
            retry: Global.en.retry
        },
        send: {
            default: "Send",
            busy: "Sending…",
            retry: Global.en.retry
        }
    };
    // src/components/Widget/index.js
    import {save, send} from "react-intl-modules-loader!./intl.js";

    // ...

    <ActionButton messages={send}/> 

Splitting

You don't have to define all of your different languages in the same file, as long as one of those language files has all the necessary keys. The combine helper will merge all the files correctly.

Hot module replacement

react-intl-modules-loader produces modules which have no imports and export only immutable data, so it should be simple to hook it up to any hot module replacement.

If you're using react-hot-loader v3, you can re-require the context module, re-run combine(), and re-render the <AppContainer> with the <IntlProvider> inside, for example:

    // src/messages.js
    const combine = require("react-intl-modules-loader/combine");
    export const locales = combine(require.context("./", true, /intl\.json$/));
    // src/intl.js
    export const en = {
        title: "My first app"
    };
    // src/App.js
    import React from "react";
    import {title} from "./intl.js";
    export const App = () => <h1><FormattedMessage id={title}/></h1>;
    // src/index.js
    import {AppContainer} from "react-hot-loader";

    function render() {
        const {locales} = require("./messages");
        const {App} = require("./App");

        ReactDOM.render(
            <AppContainer>
                <IntlProvider locale={navigator.language}
                              messages={locales[navigator.language] || locales.en}>
                    <App/>
                </IntlProvider>
            </AppContainer>,
            document.getElementById("root")
        )
    }
    render();

    if (module.hot) {
        module.hot.accept(render);
        module.hot.accept("./messages", render);
        module.hot.accept("./App", render);
    }