Skip to content

Instantly share code, notes, and snippets.

@HaNdTriX
Last active August 23, 2021 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HaNdTriX/95db16af37dd187ba42b8a4ae483dd3a to your computer and use it in GitHub Desktop.
Save HaNdTriX/95db16af37dd187ba42b8a4ae483dd3a to your computer and use it in GitHub Desktop.
// THIS IS JUST A POC. DO NOT USE THIS CODE!
module.exports = function babelPluginGenerateLanguageKatalog(api, options) {
const componentNames = ['FormattedMessage']
const functionNames = ['formatMessage']
const foundIds = new Set()
return {
inherits: require('babel-plugin-syntax-jsx'),
visitor: {
Program: {
exit(path, state) {
// TODO: Process aggregated language keys.
// Maybe by generating a manifest?
console.log(state.file.opts.filename, Array.from(foundIds))
},
},
JSXOpeningElement(path) {
const name = path.get('name')
if (!componentNames.find((n) => name.isJSXIdentifier({ name: n }))) {
return
}
const idAttr = path.node.attributes.find(
(attr) => attr.name.name === 'id'
)
foundIds.add(idAttr.value.value)
},
CallExpression(path) {
const callee = path.get('callee')
if (!isFormatMessageCall(callee, functionNames)) {
return
}
const [messageDescriptor] = path.get('arguments')
if (messageDescriptor.isObjectExpression()) {
const properties = messageDescriptor.get('properties')
const idProp = properties.find((prop) => {
const keyProp = prop.get('key')
return (
keyProp.isIdentifier({ name: 'id' }) ||
keyProp.isStringLiteral({ value: 'id' })
)
})
foundIds.add(idProp.node.value.value)
}
},
},
}
}
function isFormatMessageCall(callee, functionNames) {
if (functionNames.find((name) => callee.isIdentifier({ name }))) {
return true
}
if (callee.isMemberExpression()) {
const property = callee.get('property')
return !!functionNames.find((name) => property.isIdentifier({ name }))
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment