Skip to content

Commit

Permalink
fix(babel-plugin-formatjs): Support string literal keys for defineMes…
Browse files Browse the repository at this point in the history
…sage (#2775)
  • Loading branch information
nckcol committed Mar 30, 2021
1 parent 8c0a8d7 commit 23c564f
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 7 deletions.
Expand Up @@ -292,6 +292,12 @@ var msgs = {
escaped: defineMessage({
id: \\"escaped.apostrophe\\",
defaultMessage: \\"A quoted value ''{value}'\\"
}),
stringKeys: defineMessage({
// prettier-ignore
'id': \\"string.key.id\\",
// prettier-ignore
'defaultMessage': \\"This is message\\"
})
};
export default class Foo extends Component {
Expand Down Expand Up @@ -327,6 +333,11 @@ export default class Foo extends Component {
"description": "Escaped apostrophe",
"id": "escaped.apostrophe",
},
Object {
"defaultMessage": "This is message",
"description": "Keys as a string literal",
"id": "string.key.id",
},
],
"meta": Object {
"project": "amazing",
Expand Down
Expand Up @@ -28,6 +28,14 @@ const msgs = {
description: 'Escaped apostrophe',
defaultMessage: "A quoted value ''{value}'",
}),
stringKeys: defineMessage({
// prettier-ignore
'id': 'string.key.id',
// prettier-ignore
'description': 'Keys as a string literal',
// prettier-ignore
'defaultMessage': 'This is message',
}),
}

export default class Foo extends Component {
Expand Down
28 changes: 21 additions & 7 deletions packages/babel-plugin-formatjs/visitors/call-expression.ts
Expand Up @@ -120,12 +120,20 @@ export const visitor: VisitNodeFunction<
)

const firstProp = properties[0]
const defaultMessageProp = properties.find(prop =>
prop.get('key').isIdentifier({name: 'defaultMessage'})
)
const idProp = properties.find(prop =>
prop.get('key').isIdentifier({name: 'id'})
)
const defaultMessageProp = properties.find(prop => {
const keyProp = prop.get('key')
return (
keyProp.isIdentifier({name: 'defaultMessage'}) ||
keyProp.isStringLiteral({value: 'defaultMessage'})
)
})
const idProp = properties.find(prop => {
const keyProp = prop.get('key')
return (
keyProp.isIdentifier({name: 'id'}) ||
keyProp.isStringLiteral({value: 'id'})
)
})

// Insert ID potentially 1st before removing nodes
if (idProp) {
Expand All @@ -138,7 +146,13 @@ export const visitor: VisitNodeFunction<

// Remove description
properties
.find(prop => prop.get('key').isIdentifier({name: 'description'}))
.find(prop => {
const keyProp = prop.get('key')
return (
keyProp.isIdentifier({name: 'description'}) ||
keyProp.isStringLiteral({value: 'description'})
)
})
?.remove()

// Pre-parse or remove defaultMessage
Expand Down

0 comments on commit 23c564f

Please sign in to comment.