All Projects → rx-ts → vue-translator

rx-ts / vue-translator

Licence: MIT license
A deadly simple i18n translate plugin for Vue, ready for Server Side Rendering.

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to vue-translator

vue-inview
vue-plugin for in-view package
Stars: ✭ 100 (+455.56%)
Mutual labels:  vue-plugin
vue-plausible
Plausible Analytics Vue.js Plugin and NuxtJS Module
Stars: ✭ 107 (+494.44%)
Mutual labels:  vue-plugin
vue-filter-pluralize
Simple pluralize filter for Vue.js
Stars: ✭ 13 (-27.78%)
Mutual labels:  vue-i18n
vue-ray
Debug your Vue 2 & 3 code with Ray to fix problems faster
Stars: ✭ 48 (+166.67%)
Mutual labels:  vue-plugin
v-dropdown-menu
Dropdown menu plugin for vuejs, supported ssr.
Stars: ✭ 23 (+27.78%)
Mutual labels:  vue-plugin
vue-package-template
Boilerplate for your next, ES6 Vue.js package. Ready for npm deployments
Stars: ✭ 12 (-33.33%)
Mutual labels:  vue-plugin
vue-swimlane
A Text Swimlane plugin for Vue.js
Stars: ✭ 71 (+294.44%)
Mutual labels:  vue-plugin
vue-link
One component to link them all 🔗
Stars: ✭ 65 (+261.11%)
Mutual labels:  vue-plugin
vue-img-orientation-changer
A vue plugin that can help you display image in correct orientation.
Stars: ✭ 38 (+111.11%)
Mutual labels:  vue-plugin
vue-plugin-boilerplate
Vue Plugin Boilerplate
Stars: ✭ 120 (+566.67%)
Mutual labels:  vue-plugin
generator-vue-plugin
Yeoman generator generating vue plugin 🚀
Stars: ✭ 29 (+61.11%)
Mutual labels:  vue-plugin
vscode-vue-i18n
🔖 这个插件能够帮到你方便浏览和编写 Vue i18n
Stars: ✭ 86 (+377.78%)
Mutual labels:  vue-i18n
vue-plugin
Highlight.js Vue Plugin
Stars: ✭ 102 (+466.67%)
Mutual labels:  vue-plugin
vue-svg-inline-plugin
Vue plugin for inline replacement of SVG images with actual content of SVG files.
Stars: ✭ 30 (+66.67%)
Mutual labels:  vue-plugin
lazyload-vue
Vue Plugin for vanilla-lazyload
Stars: ✭ 29 (+61.11%)
Mutual labels:  vue-plugin
vue-jss-plugin
JSS plugin implementation for Vue.js
Stars: ✭ 24 (+33.33%)
Mutual labels:  vue-plugin
vue-cli4-webpack-template
基于vue-cli4+webpack 封装,便于下次新项目快速构建一个完备的模板项目(包含架手架引入、过滤器封装、ajax封装、路由引入封装、代理配置调试、less预编译配置引入、less主题切换、语言国际化、网页加载进度条)
Stars: ✭ 14 (-22.22%)
Mutual labels:  vue-i18n
vite-plugin-webfont-dl
⚡ Webfont Download Vite Plugin - Make your Vite site load faster
Stars: ✭ 69 (+283.33%)
Mutual labels:  vue-plugin
vue-translations
VueJs translations very similar to Laravel Translation system
Stars: ✭ 15 (-16.67%)
Mutual labels:  vue-i18n
vue-drag-zone
Drag Zone component for @vuejs
Stars: ✭ 127 (+605.56%)
Mutual labels:  vue-plugin

vue-translator

Greenkeeper badge Codecov Travis npm David David Dev code style: prettier

A deadly simple i18n translate plugin for Vue, ready for Server Side Rendering.

Demo

client side rendering: https://JounQin.github.io/vue-translator

server side rendering: https://rubick.1stg.me (source code)

Usage

yarn add vue-translator

Basic Usage

import Vue from 'vue'
import VueTranslator from 'vue-translator'

Vue.use(VueTranslator, {
  locale?: string, // set it on initialize or before first rendering
  translations?: {  // If you want to define translations in component only, no need to set it on initialize
    [locale: string]: {
      [key:string]: string | array | object
    }
  },
  defaultLocale?: string, // when no value can be found in current locale, try to fallback to defaultLocale
  filter?: boolean | string, // whether to enable filter `translate` or custom define filter name (>= 0.7.0)
  merge?: Function // `lodash.merge` for example, if you want to use component translator you must pass it
})

You will get a default translator instance on Vue.translator, it is safe to use it on client, but please avoid use it on server, be careful!

translations is often generated via require.context provided by webpack from *.{locale}.i18n.json:

const context = require.context('.', true, /([\w-]*[\w]+)\.i18n\.json$/)

const LOCALE_KEYS: { [key: string]: string[] } = {}

const translations: {
  [locale: string]: {
    [key: string]: string
  }
} = context.keys().reduce((modules: any, key: string) => {
  const module = context(key)
  const lang = key.match(/([\w-]*[\w]+)\.i18n\.json$/)[1]
  const matched = modules[lang] || (modules[lang] = {})

  if (process.env.NODE_ENV === 'development') {
    const keys = LOCALE_KEYS[lang] || (LOCALE_KEYS[lang] || [])
    const moduleKeys = Object.keys(module)

    const duplicates = _.intersection(keys, moduleKeys)

    if (duplicates.length) {
      console.warn('detect duplicate keys:', duplicates)
    }

    keys.push(...moduleKeys)
  }

  Object.assign(matched, module)
  return modules
}, {})

Then you will be able to use $t in all your component template.

<template>
  <div>
    {{ $t('message', obj_params?) }}
    {{ $t('nested.message', arr_params?) }}
  </div>
</template>
<script>
export default {
  name: 'custom-component', // it is needed for better cache for < 0.6.0, after >= 0.6.0 not required
  translator: {
    zh: {
      message: '我的信息',
    },
    en: {
      message: 'My Message',
    },
  },
}
</script>

If you are trying to get a non-exist key or value is undefined, you will get a warning in console on development. And if you want to ignore it, pass a third parameter ignoreNonExist: boolean: $t('non-exist-key', null, true).

If you want to watch locale change in any component, global watch should be defined on root component:

new Vue({
  el: '#app',
  watch: {
    '$t.locale'(curr, prev) {
      // do something
    },
  },
})

Or you want to change locale on client:

{
  methods: {
    changeLocale() {
      this.$t.locale = 'locale'
    }
  }
}

SSR related

You'd better to detect user custom locale via cookie and fallback to accept-language on first request.

And you need to generate a single translator instance for every user request (cache by locale would be better) via createTranslator, koa for example:

import { createTranslator } from 'vue-translator'

app.use(async (ctx, next) => {
  const translator = createTranslator({
    locale: string, // ctx.cookies.get('locale_cookie')
    defaultLocale: string,
  })

  const context = {} // user context

  context.translator = translator

  // ... do anything
})

Then $t will be translator generated above, if you don't mind user's locale cookie and not pass translator instance into user context, it will fallback to the default translator.

Remember, always get translator instance via this.$t of context.translator instead of Vue.translator unless you are not handling user request.

And notice implement of filter translate on server is a little hacky which overwrites Vue.prototype._f internally to get this.$t for every request.

template syntax

Translation key should be string, but .(dot) will be parsed as nested key, it will also work in template!

$t('a.b.c') // will try to find `a.b.c` on your custom transition, if a is falsy, will render undefined and try default locale

// render `nested value`
new Vue({
  translator: {
    en: {
      a: {
        b: {
          c: 'nested value',
        },
      },
    },
  },
})

// render `nested template`
$t('a.b', {c: d: 'nested template'})
new Vue({
  translator: {
    en: {
      a: {
        b: '{ c.d }'
      },
    },
  },
})

Array is also supported, .index(dot) or [index] can both be used!

// nested with array key and template
// render `1`
$t('a.b[0]', [{ a: 1 }])

new Vue({
  translator: {
    en: {
      a: {
        b: ['{ 0.a }'], // do not use `[0].a` here, `0[a]` is also OK
      },
    },
  },
})

Feature Request or Troubleshooting

Feel free to create an issue.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].