• Stars
    star
    212
  • Rank 186,122 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

i18n for the component age. Auto management react-intl ID.

babel-plugin-react-intl-auto

test Coverage Status styled with prettier tested with jest All Contributors babel-plugin-react-intl-auto Dev Token

i18n for the component age. Auto management react-intl ID.

React Intl is awesome. But, Global ID management is difficult and confusing.

Many projects, like react-boilerplate, give the ID to the name of the component as a prefix. But it is redundant and troublesome.

This babel-plugin releases you from cumbersome ID management. Based on the file path, this automatically generates a prefixed id.

Also, we strongly encourage you to use extract-react-intl-messages. You can generate json automatically.

Goodbye, global ID!!

Before

import { defineMessages, FormattedMessage } from 'react-intl'

export default defineMessages({
  hello: {
    id: 'App.Components.Greeting.hello',
    defaultMessage: 'hello {name}',
  },
  welcome: {
    id: 'App.Components.Greeting.welcome',
    defaultMessage: 'Welcome!',
  },
})

const MyComponent = () => (
  <FormattedMessage
    id="App.Components.Greeting.goodbye"
    defaultMessage="goodbye {name}"
  />
)

After

With babel-plugin-react-intl-auto.

import { defineMessages, FormattedMessage } from 'react-intl'

export default defineMessages({
  hello: 'hello {name}',
  welcome: 'Welcome!',
})

const MyComponent = () => <FormattedMessage defaultMessage="goodbye {name}" />

See examples.

With extract-react-intl-messages

Example usage with extract-react-intl-messages.

$ extract-messages -l=en -o translations 'src/**/*.js'

en.json

{
  "components.App.hello": "hello {name}",
  "components.App.welcome": "Welcome",
  "components.App.189751785": "goodbye {name}" // unique hash of defaultMessage
}

Install

npm

$ npm install --save-dev babel-plugin-react-intl-auto

# Optional: TypeScript support
$ npm install --save-dev @babel/plugin-transform-typescript

yarn

$ yarn add --dev babel-plugin-react-intl-auto

# Optional: TypeScript support
$ yarn add --dev @babel/plugin-transform-typescript

Usage

.babelrc

{
  "plugins": [
    [
      "react-intl-auto",
      {
        "removePrefix": "app/",
        "filebase": false
      }
    ]
  ]
}

with injectIntl

Input:

import { injectIntl } from 'react-intl'

const MyComponent = ({ intl }) => {
  const label = intl.formatMessage({ defaultMessage: 'Submit button' })
  return <button aria-label={label}>{label}</button>
}

injectIntl(MyComponent)

↓   ↓   ↓

Output:

import { injectIntl } from 'react-intl'

const MyComponent = ({ intl }) => {
  const label = intl.formatMessage({
    id: 'App.Components.Button.label',
    defaultMessage: 'Submit button',
  })
  return <button aria-label={label}>{label}</button>
}

injectIntl(MyComponent)

with useIntl

Input:

import { useIntl } from 'react-intl'

const MyComponent = () => {
  const intl = useIntl()
  const label = intl.formatMessage({ defaultMessage: 'Submit button' })
  return <button aria-label={label}>{label}</button>
}

↓   ↓   ↓

Output:

import { useIntl } from 'react-intl'

const MyComponent = () => {
  const intl = useIntl()
  const label = intl.formatMessage({
    id: 'App.Components.Button.label',
    defaultMessage: 'Submit button',
  })
  return <button aria-label={label}>{label}</button>
}

Options

removePrefix

remove prefix.

Type: string | boolean | regexp
Default: ''

if removePrefix is true, no file path prefix is included in the id.

Example (src/components/App/messages.js)

when removePrefix is "src"

import { defineMessages } from 'react-intl';

export default defineMessages({
  hello: 'hello world'
});

           

import { defineMessages } from 'react-intl';

export default defineMessages({
  hello: {
    id: 'components.App.hello',
    defaultMessage: 'hello world'
  }
});

when removePrefix is "src.components"

import { defineMessages } from 'react-intl';

export default defineMessages({
  hello: 'hello world'
});

           

import { defineMessages } from 'react-intl';

export default defineMessages({
  hello: {
    id: 'App.hello',
    defaultMessage: 'hello world'
  }
});

when removePrefix is true

import { defineMessages } from 'react-intl';

export default defineMessages({
  hello: 'hello world'
});

           

import { defineMessages } from 'react-intl';

export default defineMessages({
  hello: {
    id: 'hello',
    defaultMessage: 'hello world'
  }
});

filebase

Type: boolean
Default: false

if filebase is true, generate id with filename.

moduleSourceName

Type: string
Default: react-intl

if set, enables to use custom module as a source for defineMessages etc.

#74 (comment)

includeExportName

Type: boolean | 'all'
Default: false

if includeExportName is true, adds named exports as part of the id.

Only works with defineMessages.

Example
export const test = defineMessages({
  hello: 'hello {name}',
})

           

export const test = defineMessages({
  hello: {
    id: 'path.to.file.test.hello',
    defaultMessage: 'hello {name}',
  },
})

If includeExportName is 'all', it will also add default to the id on default exports.

extractComments

Use leading comments as the message description.

Only works with defineMessages

Type: boolean
Default: true

Example
export const test = defineMessages({
  // Message used to greet the user
  hello: 'hello {name}',
})

           

export const test = defineMessages({
  hello: {
    id: 'path.to.file.test.hello',
    defaultMessage: 'hello {name}',
    description: 'Message used to greet the user',
  },
})

useKey

Only works with intl.formatMessage, FormattedMessage and FormattedHTMLMessage. Instead of generating an ID by hashing defaultMessage, it will use the key property if it exists.

Type: boolean
Default: false

Example
intl.formatMessage({
  key: 'foobar',
  defaultMessage: 'hello'
});

           

intl.formatMessage({
  key: 'foobar',
  defaultMessage: 'hello',
  "id": "path.to.file.foobar"
});
<FormattedMessage key="foobar" defaultMessage="hello" />

           

<FormattedMessage id="path.to.file.foobar" key="foobar" defaultMessage="hello" />

separator

Allows you to specify a custom separator

Type: string
Default: .

Example

when separator is "_"

export const test = defineMessages({
  hello: 'hello {name}',
})

           

export const test = defineMessages({
  hello: {
    id: 'path_to_file_test_hello',
    defaultMessage: 'hello {name}',
  },
})

relativeTo

Allows you to specify the directory that is used when determining a file's prefix.

This option is useful for monorepo setups.

Type: string
Default: process.cwd()

Example

Folder structure with two sibling packages. packageB contains babel config and depends on packageA.

|- packageA
| |
|  -- componentA
|
|- packageB
| |
|  -- componentB
| |
|  -- .babelrc

Set relativeTo to parent directory in packageB babel config

{
  "plugins": [
    [
      "react-intl-auto",
      {
        "relativeTo": "..",
        // ...
      },
    ],
  ]
}

Run babel in packageB

cd packageB && babel

Messages in componentA are prefixed relative to the project root

export const test = defineMessages({
  hello: 'hello {name}',
})

           

export const test = defineMessages({
  hello: {
    id: 'packageA.componentA.hello',
    defaultMessage: 'hello {name}',
  },
})

Support variable

Example
const messages = { hello: 'hello world' }

export default defineMessages(messages)

           

const messages = {
  hello: {
    id: 'path.to.file.hello',
    defaultMessage: 'hello wolrd'
  }
};

export default defineMessages(messages);

TypeScript

TypeScript support is bundled with this package. Be sure to include our type definition and run @babel/plugin-transform-typescript beforehand. This way, you can also be empowered by extract-react-intl-messages.

tsconfig.json

{
  "compilerOptions": {
    // ...
    "jsx": "preserve"
    // ...
  },
  "include": ["node_modules/babel-plugin-react-intl-auto/**/*.d.ts"]
}

.babelrc

{
  "plugins": [["@babel/plugin-transform-typescript"], ["react-intl-auto"]]
}

webpack.config.js

Use babel-loader along with ts-loader when using webpack as well.

module.exports = {
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: [/node_modules/],
        use: [
          {
            loader: 'babel-loader',
          },
          {
            loader: 'ts-loader',
          },
        ],
      },
    ],
  },
}

Related

babel-plugin-react-intl-id-hash

If you want short consistent hash values for the ID, you can use react-intl-id-hash in addition to this plugin to help reduce your applications bundle size.

extract-react-intl-messages

Extract react-intl messages.

Contributors

Thanks goes to these wonderful people (emoji key):


akameco

💻 ⚠️ 👀 📖

Aleksander Heintz

💻 📖

Ryan Leckey

💻

Adam

💻 📖

Guylian Cox

💻 📖 ⚠️

Carl Grundberg

💡 📖

bradbarrow

💻 📖 ⚠️

Mauro Gabriel Titimoli

💻 ⚠️

Stanislav Ermakov

💻

Chitoku

💻

Kouta Kumagai

📖 💻 ⚠️

Shahyar G

💻

Remco Haszing

💻

jmarceli

💻 ⚠️
Dominik Żegleń
Dominik Żegleń

💻 ⚠️
Filip
Filip "Filson" Pasternak

💻
Eric Masiello
Eric Masiello

💻 ⚠️
Josh Poole
Josh Poole

💻 ⚠️

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT © akameco

More Repositories

1

PixivDeck

💕 pixiv client for Desktop like TweetDeck 💕
JavaScript
437
star
2

s2s

Coding time Compile. A tool to write code fastest.
JavaScript
263
star
3

pixiv-app-api

Promise base pixiv API client
TypeScript
218
star
4

extract-react-intl-messages

extract react intl messages
TypeScript
184
star
5

styled-spinkit

Spinner Loading components
TypeScript
92
star
6

styled-style

css modules like styled-components
JavaScript
91
star
7

babel-plugin-react-data-testid

babel plugin for react data-testid attributes
TypeScript
30
star
8

yamada

🐾 best image viewer while at work.
JavaScript
29
star
9

electron-load-devtool

Easily load dev tool for electron
JavaScript
24
star
10

golangify

Golang like error handling for async/await and sync function.
JavaScript
21
star
11

eslint-config-precure

ESLint shareable config for precure
JavaScript
20
star
12

reducer-tester

Utilities for testing redux reducers
TypeScript
19
star
13

extract-react-intl

Extract react-intl messages
JavaScript
18
star
14

electron-referer

Referer control for Electron app.
JavaScript
17
star
15

prioritize-yarn

If the project has yarn.lock, change npm install to yarn.
JavaScript
16
star
16

redux-actions-type

easy typing of redux action
TypeScript
15
star
17

babel-preset-zero

babelrc for zero config
JavaScript
14
star
18

pixiv-dl

pixiv image downloader
JavaScript
12
star
19

akameco

akameco CLI
JavaScript
12
star
20

babel-plugin-twitter

import from tweeeeeeet!!!!!!!!!!!!!
JavaScript
12
star
21

electron-terminal-open

Open App from Command Line Interface for Electron
Shell
11
star
22

sana-voice

さなボタンからランダムに再生するCLI
JavaScript
11
star
23

react-s3-uploader-sample

JavaScript
11
star
24

touch-alt

Create from a template instead of a new file
JavaScript
10
star
25

try-xss-electron

ElectronアプリのXSSでrm -fr /を実行する
JavaScript
9
star
26

pixiv

pixiv api client
JavaScript
8
star
27

babel-plugin-jsx-target-blank

add 'noopener noreferrer' to external link for security
JavaScript
8
star
28

yaml-flat-loader

JavaScript
8
star
29

babel-plugin-react-remove-classname

babel plugin for remove classname
TypeScript
8
star
30

pixiv-tag-downloader

タグ検索に特化したCLIのpixivの画像ダウンローダー
JavaScript
7
star
31

create-babelrc

create .babelrc using package.json
JavaScript
7
star
32

readme-gen

README generator for node.js.
JavaScript
7
star
33

npm-popute

watch 'ポプテピピック' while running npm install
JavaScript
6
star
34

twada-stand

テストを書いてない書いてない人の前に例のスタンドが現れます
JavaScript
6
star
35

pixiv-img

pixiv image downloader
JavaScript
6
star
36

kimi-no-na-ha

君の名は。
Shell
6
star
37

pixiv-dl-preview

pixivイラストダウンローダー + 画像プレビュー
JavaScript
6
star
38

s2s-plugins

s2s plugins
JavaScript
5
star
39

popute-random-img

ポプテピピックをターミナルで楽しむ
JavaScript
5
star
40

cli-to-api

transform cli to JSON API Server
JavaScript
5
star
41

babel-plugin-float-equal

Babel plugin for float equal
JavaScript
5
star
42

babel-plugin-fizzbuzz

Babel Plugin for fizzbuzz
JavaScript
5
star
43

s2s-examples

s2s examples (react,redux,flowtype...)
JavaScript
4
star
44

capture-element

JavaScript
4
star
45

jest-yaml-transform

Jest transform plugin. transform yaml to Object.
JavaScript
4
star
46

redux-observable-example

TypeScript
4
star
47

phoenix-react-sample-app

phoenix + react のサンプルアプリケーション
JavaScript
4
star
48

symphogear

cacheable mp3 player from files and url for CLI
JavaScript
3
star
49

qiita-infinite-more

Qiitaのフィードに無限スクロールを追加
JavaScript
3
star
50

read-babelrc-up

Read the closet .babelrc file
JavaScript
3
star
51

github-kusa

Check the grass of GitHub at the terminal for macOS
JavaScript
3
star
52

how-to-test-reducers

JavaScript
3
star
53

react-native-counter-with-styled-components

JavaScript
3
star
54

babel-plugin-create-redux-action-func

JavaScript
3
star
55

generator-ts-lib

Scaffold node module with TypeScript.
JavaScript
3
star
56

typed-assign

Object.assingn, Overwrite when type mismatch
JavaScript
2
star
57

koharu

小春
JavaScript
2
star
58

npm-src

ghq for npm
JavaScript
2
star
59

babel-plugin-create-redux-action-type

JavaScript
2
star
60

pixiv-auth-got

JavaScript
2
star
61

npm-cd

JavaScript
2
star
62

babel-plugin-redux-action-compose

JavaScript
2
star
63

npm-pixiv

watch pixiv daily ranking while running npm install
JavaScript
2
star
64

electron-args

CLI helper for electron
JavaScript
2
star
65

autocomplete-date

Atom autocomplete date
JavaScript
2
star
66

lux-event

get lux value by eventemitter for osx user
JavaScript
2
star
67

github-weekly-activity

TypeScript
1
star
68

greasemonkey

greasemonkey plugin
JavaScript
1
star
69

rtl-snapshot-diff-example

JavaScript
1
star
70

git-grep-edit

git grep + peco + editor
Shell
1
star
71

akameco.github.io

CSS
1
star
72

vimpr

akameco vimperator plugins
JavaScript
1
star
73

electron-updater-example

JavaScript
1
star
74

ts-sum

JavaScript
1
star
75

ambient-light

Get ambient light in OSX
JavaScript
1
star
76

babel-plugin-react-remove-classname-test

babel plugin for remove classname
JavaScript
1
star
77

gcd-cli

GitHub cd
Shell
1
star
78

redux-saga-example

JavaScript
1
star
79

natori.proxy

proxy for 名取
JavaScript
1
star
80

use-actions

redux use-actions for me
TypeScript
1
star
81

morse-jp

This is a tool that converts 'Text' and 'Morse cord' to each other
JavaScript
1
star
82

pre-notranslate

Do not translate source code chrome extension
JavaScript
1
star
83

babel-plugin-s2s-action-creater

generate action creater
JavaScript
1
star
84

envrc-to-interface

TypeScript
1
star
85

find-data-test

JavaScript
1
star
86

ptils

utils for package.json
TypeScript
1
star
87

eslint-config-zero

eslint-config-zero
JavaScript
1
star
88

babel-plugin-react-path-display

babel plugin for react display name with file path prefix.
JavaScript
1
star
89

webpack-config-type-definition-example

JavaScript
1
star
90

Brewfile

Auto backup Brewfile by launchd.
Ruby
1
star
91

redux-async-qiita

redux async example with qiita api
JavaScript
1
star
92

babel-plugin-console-with-loc

babel plugin for console.log with loc
JavaScript
1
star
93

dotfiles

dotfiles
Vim Script
1
star
94

jamstack-intro

HTML
1
star
95

electron-github-actions

JavaScript
1
star
96

abematron

abema.tv for desktop
JavaScript
1
star
97

epic-tester

easy Epic test
JavaScript
1
star
98

jest-yaml-flat-transfrom

JavaScript
1
star
99

add-author-to-all-contributors

JavaScript
1
star
100

styled-style-example

JavaScript
1
star