DEV Community

Cover image for Announcing vue-inter 3.0
EGOIST
EGOIST

Posted on

Announcing vue-inter 3.0

vue-inter is an i18n library that is made exclusively for Vue.js, weighs only 1kB in size.

Code always speaks louder than words, let me give an example:

Here's your app entry index.js:

import Vue from 'vue'
import Inter from 'vue-inter'
import Greeting from './Greeting.vue'

Vue.use(Inter)

const inter = new Inter({
  locale: 'en',
  // Messages for other locales
  messages: {}
})

new Vue({
  inter,
  render: h => h(Greeting)
})
Enter fullscreen mode Exit fullscreen mode

Typically you would directly write message for default locale in your view layer, so there's no need to define messages for default locale when creating the inter instance.

Here's your view Greeting.vue:

<template>
  <div>
    <format-message
      path="app.greeting"
      defaultMessage="Hello {name}!"
      :data="{name: 'egoist'}"
    />
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

With this it will be rendered as follows:

<div><span>Hello egoist!</span></div>
Enter fullscreen mode Exit fullscreen mode

Add a new locale

First you need to define relevant messages when creating the inter instance:

new Inter({
  locale: urlQuery.lang || 'en',
  messages: {
    // e.g. Add `cn` for Chinese
    cn: {
      app: {
        greeting: '你好 {name}'
      }
    }
  }
})
Enter fullscreen mode Exit fullscreen mode

Now visit ?lang=cn and you will get:

<div><span>你好 egoist!</span></div>
Enter fullscreen mode Exit fullscreen mode

Edit Vue Template

Plural support

You can use intl-messageformat for extra plural support:

import IntlMessageFormat from 'intl-messageformat'

const inter = new Inter({
  template(message, data) {
    if (!data) return message
    const tpl = new IntlMessageFormat(message, this.currentLocale)
    return tpl.format(data)
  }
})
Enter fullscreen mode Exit fullscreen mode

Now you can use such syntax in locale messages:

<format-message
  path="app.showApples"
  defaultMessage="You have {num, plural, 
    =0 {no apples.}
    =1 {one apple.}
    other {# apples.}
  }"
  :data="{num: 10}"
/>
Enter fullscreen mode Exit fullscreen mode

Note that you may need to polyfill Intl and load locale data for non-English languages.

Use the API directly

You can directly access your Inter instance as this.$inter in your component, e.g.:

// Switch to `cn` locale
this.$inter.setCurrentLocale('cn')
Enter fullscreen mode Exit fullscreen mode

See API for more details.

Differences with vue-i18n

  • vue-inter is simple, minimal and blazing fast, 980B compared to vue-i18n's 5kB in size (gzipped)
  • Plural/Datetime support is optional in vue-inter (that's why it's so small!)

Links:

Top comments (0)