babel-plugin-react-intl-auto
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