Skip to content

Commit c0c08ba

Browse files
author
Sergio
committed
feat: accept t as function
1 parent eb68e51 commit c0c08ba

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

packages/macro/src/macroJs.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,11 @@ export default class MacroJs {
9898
return
9999
}
100100

101+
if (this.types.isCallExpression(path.node) && this.isIdentifier(path.node.callee, "t")) {
102+
this.replaceTAsFunction(path)
103+
return
104+
}
105+
101106
const tokens = this.tokenizeNode(path.node)
102107

103108
const messageFormat = new ICUMessageFormat()
@@ -142,6 +147,26 @@ export default class MacroJs {
142147
path.replaceWith(descriptor)
143148
}
144149

150+
/**
151+
* macro `t` is called with MessageDescriptor, after that
152+
* we create a new node to append it to i18n._
153+
*/
154+
replaceTAsFunction = (path) => {
155+
const descriptor = this.processDescriptor(path.node.arguments[0])
156+
const newNode = this.types.callExpression(
157+
this.types.memberExpression(
158+
this.types.identifier(this.i18nImportName),
159+
this.types.identifier("_")
160+
),
161+
[descriptor]
162+
)
163+
164+
this.addExtractMark(path)
165+
166+
// @ts-ignore
167+
path.replaceWith(newNode)
168+
}
169+
145170
/**
146171
* `processDescriptor` expand macros inside messsage descriptor.
147172
* Message descriptor is used in `defineMessage`.

packages/macro/test/js-t.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,28 @@ export default [
8282
i18n._("Multiline\\nstring")
8383
`,
8484
},
85+
{
86+
name: "Support id and comment in t macro as callExpression",
87+
input: `
88+
import { t } from '@lingui/macro'
89+
t({
90+
id: 'msgId_2',
91+
message: 'text',
92+
comment: 'description for translators'
93+
})
94+
t({ id: 'msgId', comment: 'description for translators', message: plural(val, { one: '...', other: '...' }) })
95+
`,
96+
expected: `
97+
import { i18n } from "@lingui/core"
98+
/*i18n*/
99+
i18n._({ id: "msgId_2", message: 'text', comment: 'description for translators' })
100+
101+
/*i18n*/
102+
i18n._({ id: "msgId", comment: 'description for translators', message: '{val, plural, one {...} other {...}}', values: {
103+
val: val,
104+
} })
105+
`,
106+
},
85107
{
86108
name: "Newlines after continuation character are removed",
87109
filename: "js-t-continuation-character.js",

0 commit comments

Comments
 (0)