- Notifications
You must be signed in to change notification settings - Fork2
Keep your translations in line - with Preact!
License
Download/preact-i18nline
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
██████╗ ██████╗ ███████╗ █████╗ ██████╗████████╗ ██╗ ███╗ ██╗██╗ ██╗███╗ ██╗███████╗ ██╔══██╗██╔══██╗██╔════╝██╔══██╗██╔════╝╚══██╔══╝ ██║ ████╗ ██║██║ ██║████╗ ██║██╔════╝ ██████╔╝██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║18 ██╔██╗ ██║██║ ██║██╔██╗ ██║█████╗ ██╔═══╝ ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ╚════╝ ██║ ██║╚██╗██║██║ ██║██║╚██╗██║██╔══╝ ██║ ██║ ██║███████╗██║ ██║╚██████╗ ██║ ██║ ██║ ╚████║███████╗██║██║ ╚████║███████╗ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝╚══════╝╚═╝╚═╝ ╚═══╝╚══════╝ keep your translations in line - with preact!
preact-i18nline bringsI18nlinetoPreact via the htmltranslate
attribute.I18n doesn't get any easier than this.
preact-i18nline lets you do this:
<ptranslate="yes"> Hey {this.props.user.name}! Although I am<Linkto="route">linking to something</Link> and have some<strong>bold text</strong>, the translators will see<strong><em>absolutely no markup</em></strong> and will only have a single string to translate :o</p>
Write your components as you normally would, and just put atranslate="yes"
attribute on any element/component that needs to belocalized. Seriously.
And because the default translation is inline, it will be used as afallback if a translation is missing or hasn't happened yet.
Best of all, you don't need to maintain separate translation filesanymore; I18nline will do it for you.
This project is a port ofreact-i18nliner byJon Jensen toPreact, a 3kB alternativeto React.
preact-i18nlinepreprocessesyour JSX, transforming it into something truly localizable. It infersplaceholders for expressionsandwrappers for elements/components,and separates the localizable string.At runtime,it localizes the string, interpolating thewrappersandplaceholders into the correct locations.
Localizable strings are detected both from the text nodes, as well as fromtranslatable attributes within thetranslate="yes"
element.
preact-i18nline enhances I18nline, so that it can extract any of thesetranslate="yes"
strings from your codebase (in addition to regularI18n.t
calls). Once you get everything translated, just stick it onI18n.translations
and everything will Just Work™.
To setup a project withpreact-i18nline
, we mostly follow thei18nline
project setup, with some small changes. The overview of the setup is repeatedbelow, but for most steps please refer to thei18nline project setup docs.
- Install
i18nline
andpreact-i18nline
(see next section) - Create a
script
inpackage.json to run the command-line tool (see i18nline docs) - Add the
preact-i18nline/webpack-loader
to your Webpack configuration - Import
I18n
and usetranslate="yes"
to render internationalized text. - Create an empty file in the
out
folder (by default:'src/i18n'
) named'[locale].json'
for each locale you want to support. (see i18nline docs) - Run
i18nline synch
to synch the translation files and index file. (see i18nline docs) import
the index file into your project. (see i18nline docs)- Call
I18n.changeLocale
to set the locale (which loads the righttranslation file on demand, see i18nline docs) - Call
I18n.on
to react to the'change'
event (e.g. by re-rendering) (see i18nline docs) - Get your translators to translate all the messages :)
npm install -S i18nline preact-i18nline
Addthis loaderto your config, e.g.
webpack.config.js
{module:{loaders:[{test:/\.js$/,loader:"preact-i18nline/webpack-loader"}...],}, ...}
If your app is generated with Preact CLI, Webpack is configured and managedfor you. So instead of configuring Webpack directly, we configure Preact CLI:
preact.config.js
exportdefault(config,env,helpers)=>{// Use Preact CLI's helpers object to get the babel-loaderletbabel=helpers.getLoadersByName(config,'babel-loader')[0].rule;// Update the loader config to include preact-i18nlinebabel.loader=[{// create an entry for the old loaderloader:babel.loader,options:babel.options},{// add the preact-i18nline webpack loaderloader:'preact-i18nline/webpack-loader'}];// remove the old loader optionsdeletebabel.options;};
In the Javascript files you want to translate, import I18n:
importI18nfrom'i18nline';
Then, write your JSX and addtranslate="yes"
to any elementsyou want to translate:
src/app/Greeting.jsx
import{h}from'preact';importI18nfrom'i18nline';constUser=props=>(<b>{props.name}</b>)constGreeting=props=>(<pclass="greeting"translate="yes"> Hello,<Username="Bob"/>!</p>);exportdefaultGreeting;
Now you are ready to generate the translation files. Run thei18nline synch
command via the script you setup inpackage.json:
$ npm run i18n
This will generate 3 files for you (insrc/18n
by default):
default.json
: the default translations extracted from the sourceen.json
: the translation file for the default locale ('en'
by default)index.js
: the index file to import into your project
To add additional languages, just add empty files named[locale].json
(e.g.'fr.json'
,'de.json'
, etc) in the same folder and runi18nline synch
again.i18nline
will populate the empty files withthe default translations.
To learn how to change locales and listen to locale change events,refer to thei18nline documentation.
A placeholder will be created for the input:
<labeltranslate="yes"> Create<input/> new accounts</label>
As well as for arbitrary JSX expressions:
<divtranslate="yes"> Welcome back, {user.name}.</div>
By default, placeholder keys will be inferred from the content, so atranslator would see"Create %{input} keys"
and"Welcome back, %{user_name}"
. For complicated expressions, these placeholder keys canget a bit long/gnarly. Having to retranslate strings that "changed" justbecause you refactored some code is terrible, so you can use keys tobe a bit more explicit:
<labeltranslate="yes"> Create<inputkey="numAccounts"onChange={this.addAccounts}/> new accounts</label>
In this case the extracted string would just be"Create %{num_accounts} new accounts"
Translators won't see any components or markup; they will be replaced witha simple wrapper notation. In this example, the extracted string would be"That is *not* the right answer"
:
<divtranslate="yes"> That is<b>not</b> the right answer</div>
In addition to the"Edit your settings *here*"
string, the"Your Account"
will also be preprocessed, since it is a validtranslatable attributewithin a translated element.
<divtranslate="yes"> Edit your settings<ahref="/foo"title="Your Account">here</a></div>
From version 2 onwards,i18nline
andpreact-i18nline
should beeffectively zero configuration for most projects. Stuff should Just Work.
If you find you need to change the configuration, you can configurei18nline throughpackage.json,i18nline.rc or command line arguments.
If multiple sources of configuration are present, they will beapplied in this order, with the last option specified overwritingthe previous settings:
- Defaults
- package.json
- .i18nrc file
- CLI arguments
Refer to thei18nline configuration docs for details.
Since version 2,i18nline
supports auto-config of plugins by lookingat the dependencies for your project. So it will automatically detectpreact-i18nline
for you. You don't have to do anything for it. Butjust for completeness, here is how you would configure thepreact-18nline
plugin if you wanted to do it explicitly:
package.json
{"i18n": {"plugins": ["preact-i18nline" ] }}
In addition to thei18nline configuration,preact-i18nline adds some options specific to JSX processing:
An array of strings, or a string with (a comma separated list of)tag names that should be translated automatically. Defaults to[]
.
package.json
{"i18n": {"autoTranslateTags": ["h1","h2","h3","h4","h5","h6","p"] }}
These tags will have an implicittranslate="yes"
, keeping your markupsimple.
Note that this works for both regular HTML elements, as well as for yourown custom components. For example, if you decided you wanted to use a<T>
component everywhere instead oftranslate="yes"
, you could add itto autoTranslateTags, and its runtime implementation could be as simpleas:
constT=(props)=>(<span{...this.props}/>)
An array of strings, or a string with (a comma separated list of)tag names that shouldnot be translated automatically.Defaults to[]
.
Similarly toautoTranslateTags
, if you have certain tags youdon't want to translate automatically, (e.g.<code>
),you can specify those in a similar manner.
package.json
{"i18n": {"neverTranslateTags": ["code"], }}
If those are ever nested in a larger translatable element, theywill be assumed to be untranslatable, and a placeholder will be createdfor them.
preact-i18nline
mainly focuses on Webpack for it's tool support. There is somesupport for Browserify (untested) or you can roll your own integration.
There is some support for Browserify throughthis transform,e.g.
$ browserify -t preact-i18nline/browserify-transform app.js> bundle.js
However, to be honest it was inherited fromreact-i18nliner
and I'm not usingit myself and haven't tested it in ages so your mileage may vary. If you do useit, please report any issues you may find (and be prepared to make a PR for it).
It's not too hard to roll your own tool support; as you can see in theloader and transform above, the heavy lifting is done bypreprocess
.So whether you use ember-cli, sprockets, grunt concat, etc., it'srelatively painless to add a little glue code that runs preprocesson each source file.
Both i18nline and preact-i18nline add some extensions to i18n.js tohelp with the runtime processing of the translations.
When you follow the recommended project setup you should not have to worryabout this.i18nline
will automatically detectpreact-i18nline
andmodify the generated index file to importI18n
frompreact-inline/i18n
instead of fromi18nline
. That will automatically take care of things.However if you want more control or are not using the generated index file,you can require I18n via preact-i18nline to get aI18n
object that has allextensions applied already:
varI18n=require("preact-i18nline/i18n");
You only need to do this in one place (e.g. in your app's main file), becausethe returned instance is actually the same object as is returned byi18nline
.preact-i18nline
just adds its extensions to it.
Alternatively, you can apply the extensions manually:
varI18n=// get it from somewhere, script tag, whatever// if you did not get it from `i18nline`, you need to apply// the i18nline extensions manually as wellrequire('i18nline/lib/extensions/i18n_js')(I18n);// finally apply the preact-i18nline extensionsrequire('preact-i18nline/dist/extensions/i18n_js')(I18n);
Since preact-i18nline is just an i18nline plugin, you can use the i18nlineCLI to extract translations from your codebase; it will pick up normalI18n.t
usage, as well as your newtranslate="yes"
components. Theeasiest way to do this is to add a"scripts"
section to your package.jsonand call i18nline from there:
package.json
{"scripts": {"i18n":"i18nline synch" }}
Then you can simply invoke it via NPM as usual:
$ npm run i18n
Refer to thei18nline project setup docsfor more information.
i18nline does support basic pluralization (via i18n-js), but you needto use pure js for that, e.g.
<div> {I18n.t({one: "You have 1 item", other: "You have %{count} items"}, {count: theCount})}</div>
This kind of gets to a general rule of i18n: don't concatenate strings.For example,
return(<btranslate="yes"> You are{this.props.isAuthorized ?"authorized" :"NOT authorized"}</b>);
The extracted string will be"You are %{opaque_placeholder}"
and thetranslators won't get a chance to translate the two inner strings (muchless without context). So don't do that; whenever you have logicallydifferent sentences/phrases, internationalize them separately, e.g.
return(this.props.isAuthorized ?<btranslate="yes">You are authorized</b> :<btranslate="yes">You are NOT authorized</b>);
NOTE: A subsequent release of preact-i18nline may add a check forthis situation that will cause ani18nline:check
failure.You've been warned :)
This project's eslint settings force a check on the use of linefeed charactersthat will fail when the project is cloned with the gitcore.autocrlfsetting set totrue
, which is the default on Windows. So make sure to changethat setting beforehand. The easiest way to do this is probably togit init
a newrepo for this project and change the setting, and only then add this repo as aremote and pull from it.
Copyright (c) 2016 by Stijn de Witt and Jon Jensen, released under the MIT license
About
Keep your translations in line - with Preact!
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Languages
- JavaScript100.0%