Skip to content

Simplifies adding translations to React projects with `react-intl`. Extracts text and creates FormatJS-compatible hint modules, ideal for large projects introduces translations later. It  can be used as a pre-processor for https://github.com/formatjs/babel-plugin-react-intl which inspired this huge time saving automation

License

Notifications You must be signed in to change notification settings

p10ns11y/babel-plugin-react-intl-messages-generator

Repository files navigation

babel-plugin-react-intl-messages-generator

Build skeleton messages files with defineMessage format for each component that contains explicit texts

Installation

$ npm install babel-plugin-react-intl-messages-generator

Usage

This Babel plugin only visits ES6 JSX modules.

All the explicit texts will be extracted from the component and corresponding messages file generated.

// app/components/Foo.js
import React, {Component} from 'react';

export default class Foo extends Component {
  render() {
    return (
      <div>
        <span>Hello</span>
        world
      </div>
    );
  }
}

The above component will produce

import { defineMessages } from 'react-intl';

export default defineMessages({
  NameTheKey: {
    id: 'app.components.Foo...',
    defaultMessage: 'Hello'
  },
  NameTheKey: {
    id: 'app.components.Foo...',
    defaultMessage: 'world'
  },
});

Via .babelrc (Recommended)

.babelrc

{
  "plugins": [
    ["react-intl-messages-generator", {
        "messagesDir": "./build/messages/"
    }]
  ]
}

(Confidently Recommended 😏)

Even better use the root directory ["messagesDir": "./"] so it will place the messages file where the component exists. So they files are co-located. No worries if you have edited the file already. Only new unique defaultMessage appended as descriptor at the end of previous list of descriptors

Options

  • messagesDir: The target location where the plugin will output a .js file corresponding to each component from which messages were extracted. If not provided, the extracted message descriptors will only be accessible via Babel's API.

Via CLI

$ babel --plugins react-intl-messages-generator script.js

Via Node API

The explicit texts converted as descriptors are available via the metadata property on the object returned from Babel's transform() API:

require('babel-core').transform('code', {
  plugins: ['react-intl-messages-generator']
}) // => { code, map, ast, metadata['react-intl-defineMessages'].generatedDescriptors };

About

Simplifies adding translations to React projects with `react-intl`. Extracts text and creates FormatJS-compatible hint modules, ideal for large projects introduces translations later. It  can be used as a pre-processor for https://github.com/formatjs/babel-plugin-react-intl which inspired this huge time saving automation

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published