1.0.0 • Published 6 years ago

babel-plugin-jsx-translate v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

babel-plugin-jsx-translate CircleCI

Less visual noise in code for translations inside JSX

Cane be combined with babel-plugin-jsx-simple and also probably could be used with React or Vue JSX.

Plugin

The code for the plugin is so simple, I am pasting it here

module.exports = function (babel) {
  var t = babel.types
  return {
    visitor: {
      JSXExpressionContainer (path) {
        if(t.isStringLiteral(path.node.expression)){
          path.node.expression = t.callExpression(t.identifier('t'),[path.node.expression]);
        }
      },
    }
  }
}

Check an example using the very nice tool ASTExplorer

If you have JSX that needs some strings translated and a function t in the scope, you can write sth like this

function render(){ 
  return <an id="id1" title={'translate_title'}>
    <Component>{'translate_me'}</Component>
  </an>
}

and it will be converted to this

function render(){ 
  return <an id="id1" title={t('translate_title')}>
    <Component>{t('translate_me')}</Component>
  </an>
}

You might say that there is not much difference, but that is your choice for your project.

I find that putting a StringLiteral in a JSX expression something I will not likely use, so I made this plugin to use instead of the one that I created bofore this one babel-plugin-translate-mi2.

In my first plugin attempt babel-plugin-translate-mi2 I used a syntax like [[translation_code]], but run into problems keeping sourcemap info correct due to way the JSXText is parsed in bybylon parser.