Improve JS macro
See original GitHub issueIs your feature request related to a problem?
Consider existing implementation:
import { setupI18n } from '@lingui/core'
import { t } from '@lingui/macro'
const i18n = setupI18n()
i18n._(t`Hello`)
This implementation has several disadvantages:
- you have to explicitly import all i18n formatters (
t
,plural
) - the
i18n._(t'Hello')
construct is just more complex that previousi18n.t
Describe the solution you’d like
import i18n from '@lingui/macro'
i18n`Hello ${world}`
This will be transformed to:
import i18n from '@lingui/core'
i18n._('Hello {world}', { world })
i18n
is a single entry macro. @lingui/core
package exports global i18n object which all macros use implicitly.
Describe alternatives you’ve considered
// i18n object extends the runtime i18n object, so all runtime methods are accessible as well:
i18n.activate('en')
i18n.load('en', catalog)
i18n.locale
// On top of core i18n API, there're these formatters:
// Basic usage
i18n`Hello ${world}`
// Override auto-generated ID
i18n('id')`Hello ${world}`
// Plurals and other formatters
i18n.plural({
// Override auto-generated ID
// id: 'custom id',
value: 1,
// template strings inside macros are processed as if they were wrapped in i18n`...` tag
one: `${name} owns one book`,
other: `${name} owns # books`
})
Additional context
Optional I18nProvider and withI18n/I18n consumers
Thanks to global i18n
object, we can make I18nProvider
completely optional. It’ll be required only if you want to re-render your app on locale change without refresh.
Global variable
If global i18n object becomes a problem, we can make createI18nMacros
function, which takes custom i18n object as an argument and creates a custom macro:
// This file must be named `*.macro.js` to be recognized as a macro
// i18n.macro.js
import { setupI18n, createI18nMacros } from '@lingui/core'
// custom i18n instance
const i18n = setupI18n()
export default createI18nMacros(i18n)
// app.js
import i18n from `./i18n.macro.js
i18n`Hello World`
Honestly, I’m not concerned much about using i18n
global and it really simplifies the API a lot. First, there’s a possible escape hatch. And second, I saw Parkour Atlas from Boston Dynamics today and I think global variables are nothing to be worried about nowadays.
This is a follow up from #353. Feedback appreciated @FredyC @vonovak @MartijnHols @queicherius (I remember having discussion with you about plugins/macros API, hence the mention. Please unsubscribe if I mentioned you by mistake)
Issue Analytics
- State:
- Created 5 years ago
- Comments:26 (25 by maintainers)
Top GitHub Comments
What about this?
This was early proposal of macros.
Resolved in #499