Skip to content

Commit

Permalink
feat: accept t as function
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergio committed Nov 2, 2020
1 parent eb68e51 commit c0c08ba
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
25 changes: 25 additions & 0 deletions packages/macro/src/macroJs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,11 @@ export default class MacroJs {
return
}

if (this.types.isCallExpression(path.node) && this.isIdentifier(path.node.callee, "t")) {
this.replaceTAsFunction(path)
return
}

const tokens = this.tokenizeNode(path.node)

const messageFormat = new ICUMessageFormat()
Expand Down Expand Up @@ -142,6 +147,26 @@ export default class MacroJs {
path.replaceWith(descriptor)
}

/**
* macro `t` is called with MessageDescriptor, after that
* we create a new node to append it to i18n._
*/
replaceTAsFunction = (path) => {
const descriptor = this.processDescriptor(path.node.arguments[0])
const newNode = this.types.callExpression(
this.types.memberExpression(
this.types.identifier(this.i18nImportName),
this.types.identifier("_")
),
[descriptor]
)

this.addExtractMark(path)

// @ts-ignore
path.replaceWith(newNode)
}

/**
* `processDescriptor` expand macros inside messsage descriptor.
* Message descriptor is used in `defineMessage`.
Expand Down
22 changes: 22 additions & 0 deletions packages/macro/test/js-t.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,28 @@ export default [
i18n._("Multiline\\nstring")
`,
},
{
name: "Support id and comment in t macro as callExpression",
input: `
import { t } from '@lingui/macro'
t({
id: 'msgId_2',
message: 'text',
comment: 'description for translators'
})
t({ id: 'msgId', comment: 'description for translators', message: plural(val, { one: '...', other: '...' }) })
`,
expected: `
import { i18n } from "@lingui/core"
/*i18n*/
i18n._({ id: "msgId_2", message: 'text', comment: 'description for translators' })
/*i18n*/
i18n._({ id: "msgId", comment: 'description for translators', message: '{val, plural, one {...} other {...}}', values: {
val: val,
} })
`,
},
{
name: "Newlines after continuation character are removed",
filename: "js-t-continuation-character.js",
Expand Down

0 comments on commit c0c08ba

Please sign in to comment.