Internationalization (i18n) & Localization (l10n)

It seams that Strawman's proposal is dictating the future of internationalization and localization in Javascript. It's using ECMAScript Internationalization API which is supported by all modern browsers and `Node.js`.

This chapter explains how to add `i18n` and `l10n` support into your Vue.js application using vue-translated.

Getting Started

Install the dependencies.

$ npm install --save vue-translated translated

Create a new file `./src/app/i18n/index.js` and configure the plugin.

import Vue from 'vue';
import {I18n} from 'translated';
import VueTranslated from 'vue-translated';

Vue.use(VueTranslated);

const locale = 'en-US'; // replace this with `process.env.LOCALE` or similar
const messages = require(`./messages/${locale}`).default;
const formats = require(`./formats/${locale}`).default;

export default new I18n({locale, messages, formats});

Create a new file `./src/app/i18n/messages/en-US.js` and define translated messages using the ICU Message Format.

export default {
  'home.text': 'Hello {name}!'
}

Create a new file `./src/app/i18n/formats/en-US.js` and define custom formats.

export default {
  number: {},
  date: {},
  time: {}
}

Open the application main file `./src/app/index.js` and attach the `i18n` instance.

import i18n from './i18n';

export const app = new Vue(
  Vue.util.extend({
    i18n,
    ...
  }, App)
);

You can now use the nee API.

<template>
  <div>
    {{ $formatMessage('home.text' {name: 'John'}) }}
  </div>
</template>

Intl Support

Browsers

If you need to support old browsers with no support for `Intl` then you need to include a polyfill. The easiest way is to use FT Polyfill Service. If you've follow this book and you are using server-side rendering then open the `./src/server/middlewares/app.js` and load the `polyfill.io` service.

exports.appServer = function () {
  return (req, res) => {
    ...
    page.on('end', () => {
      res.write(`<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en"></script>`);
      ...
    });
    ...
  };
};

Node.js

Node.js already supports `Intl` out of the box but it comes with English support only. To support other languages we need to download the latest ICU data file and then run our scripts with the `--icu-data-dir` option.

To enable other languages in your Vue.js application on the server-side, first download the ICU data.

$ npm install --save icu4c-data@0.58.2

Open the `./package.json` file and update your `node` scripts by adding the `--icu-data-dir` option.

{
  "scripts": {
    ...
    "start": "node --harmony --icu-data-dir=node_modules/icu4c-data ./scripts/start"
  },
}

results matching ""

    No results matching ""