A webpack loader i18n solution for Vue (Nuxt) with auto generated keysA webpack loader i18n solution for Vue (Nuxt) with auto generated keys

Related tags

Nuxt vue-i18n-loader
Overview

vue-i18n-loader - another webpack loader i18n solution for Vue (Nuxt) with auto generated keys.

Currently under development, pull requests and suggestions are welcome.

Documentation in Chinese 中文文档

Why?

  • We need auto generated keys for texts to be translated

    There are only two hard things in Computer Science: cache invalidation and naming things. -- Phil Karlton

    Most i18n solutions ask developers to name each text with a unique key, like $t("message.hello"), naming is so annoying, it's not reasonable to waste time doing this job

  • Text translations should be put just beside source codes

    Some solutions extract all texts to a single json file, it's not conform to modularization

How it works?

  1. Find automatically texts to translate by two means: regex string or 'delimiter'(Refer to usage below).
  2. Keep first 8 characters of every matched text as key (and append 4 characters md5 hash to the key if the text is longer than 8)
  3. Replace texts by translator markups using regex
  4. Create or update filename.messages.json to store translations, import this file in filename.vue

!!! Attentions !!!

  • Since this at the top level of es6 module bind to undefined, but not the vue instance.

    All target texts in script part should be put in functions(not fat arrow functions refer to this doc)

Usage

Config webpack

Config example based on Nuxt.js.

Given regString, the loader will match all texts/attributes/string templates by new RegExp(regString)

Given delimiter, the loader will ignore regString, The loader will match all texts between delimiter, for example ##text##.

    {
        test: /\.vue$/,
        exclude: [/node_modules/],
        loader: 'vue-i18n-loader',
        enforce: 'pre',
        options: {
          updateMessagesFile: ctx.isClient && ctx.isDev, // only update messages file when it's dev and client(when using ssr)
          cacheTime: 3000,
          // regString to match simplified chinese characters
          regString: '[\u4e00-\u9fa5\u3002\uff1b\uff0c\uff1a\u2018\u2019\u201c\u201d\uff08\uff09\u3001\uff1f\uff01\ufe15\u300a\u300b]+',
          // delimiter: '##', // match texts surrounded by '##', like '##text##'
          // Loader will use existing translations, if there is not, will use text generated by translator
          languages: [{
            key: 'zh_Hans_CN',
            translator: (matched) => {
              // Delete repeat mark R, sometimes we need a text to be translated differentlyz`
              return matched.replace(/^\[R\]+/, '')
            }
          }, {
            key: 'zh_Hant_HK',
            translator: (matched) => {
              // example to auto translate simplified chinese to traditional
              return chineseS2T.s2t(matched.replace(/^\[R\]+/, ''))
            }
          }, {
            key: 'en_US',
            // if translator is not given, the loader will use the default translator(translator of the first language, zh_Hans_CN here)
          }],
        }
      }

Add a global plugin to tell our helper which language to show

An example of plugin can be:

    import Vue from 'vue';
    import {mapGetters} from 'vuex';

    // !!! the key must be $lang, which will be referenced by the helper !!!
    Vue.mixin({
      computed: {
        ...mapGetters({'$lang': 'currentLang'}),
      }
    });

The helper will insert code automatically to refer this $lang variable like this:

    methods:{
        $t(key){
              if(!this.$lang && !messages["${defaultLang}"]) return key;
              const trans = messages[this.$lang]||messages["${defaultLang}"]||{};
              return trans[key];
        },
    }

defaultLang is the first language key set in config, zh_Hans_CN here in the example.

Demo

check the example directory:

  1. This example is based on Nuxt.js
  2. Download this example and start by npm install then npm run dev
  3. Try changing texts and add some translations

Cli tool

We provide a cli tool to group all *.messages.json and serve a web page for human translators Please refer to the github repo of viai18n-cli

Roadmap

  • Support JSX
  • Add tests
You might also like...
WordPress module for Nuxt.js with full support for SSR and Nuxt.js PWA module.

WordPress module for Nuxt.js with full support for SSR and Nuxt.js PWA module.

🖼Portfolio built with Nuxt and Nuxt Content

🖼Portfolio built with Nuxt and Nuxt Content

Kirby Nuxt Starter Kit - Kirby's sample site – but rewritten headless with Nuxt 3

Kirby Nuxt Starter Kit Kirby's sample site – but rewritten headless with Nuxt 3! Explore the kit live » Kirby Nuxt Starterkit This repository is a por

Nuxt + CoreUI Free Vue Bootstrap Admin TemplateNuxt + CoreUI Free Vue Bootstrap Admin Template
Nuxt + CoreUI Free Vue Bootstrap Admin TemplateNuxt + CoreUI Free Vue Bootstrap Admin Template

Nuxt + CoreUI Free Vue Bootstrap Admin Template Nuxt + CoreUI Free Vue Bootstrap Admin Template Description Nuxt + CoreUI Free Vue Bootstrap Admin Tem

 Metamask, Trustwallet in Vue Nuxt Ethers
Metamask, Trustwallet in Vue Nuxt Ethers

Exchange Build Setup # install dependencies $ npm install # serve with hot reload at localhost:3000 $ npm run dev # build for production and launch

Responsive ecommerce template built with Vue.js and Nuxt.js
Responsive ecommerce template built with Vue.js and Nuxt.js

Vuemmerce - Ecommerce Template Responsive ecommerce template built with Vue.js and Nuxt.js Installing # clone repository git clone https://github.com/

🏕 Vitesse experience for Nuxt 2 and Vue 2
🏕 Vitesse experience for Nuxt 2 and Vue 2

Vitesse Nuxt Bridge Vitesse experience for Nuxt 2 and Vue 2. 🧪 Experimental Nuxt 3 version Features 💚 Nuxt Bridge - Experience Nuxt 3 features on ex

 Movies Store App (Vue + Nuxt.js + Vuex + Appbase)
Movies Store App (Vue + Nuxt.js + Vuex + Appbase)

Build an end-to-end e-commerce App with Vue, Nuxt, and appbase.io (for building search). Uses Auth0 for authentication, Stripe for checkout, and Heroku / Vercel for deployment.

Github'st Development Archive Application using vue and nuxt
Github'st Development Archive Application using vue and nuxt

cat-hub Github'st Development Archive Application using vue and nuxt. Link You can check here. Tech and libraries vue vuex vuetify sass nuxt nuxt/cont

Owner
BitApp
BitApp
Make your Nuxt.js webpack builds faster ⚡

nuxt-webpack-optimisations Previously: "nuxt-build-optimisations", see migration notes. Instantly speed up your Nuxt.js webpack build time. Can't use

Harlan Wilton 255 Dec 16, 2022
This is nuxt invoice app using nuxt.js and firebase

Nuxt Invoice App Build Setup # install dependencies $ npm install # serve with hot reload at localhost:3000 $ npm run dev # build for production and

Moein Salari 8 Dec 20, 2022
nuxt-fullpage is a nuxt module for creating fullscreen page scroll fast and simple.

Nuxt fullpage Nuxt module for creating fullscreen page scroll fast and simple. Demo online Table of contents Installation Usage Options Contributing I

Open Source Afghanistan 16 Dec 30, 2022
A simple nuxt renderless component wrapper around nuxt fetch capabilities

Nuxt Fetch Component A simple nuxt renderless component wrapper around nuxt fetc

Mathieu Marteau 6 Apr 12, 2022
Nuxt basic - Simple Nuxt.js project

nuxt_basic Build Setup # install dependencies $ npm install # serve with hot reload at localhost:3000 $ npm run dev # build for production and launc

null 2 Oct 20, 2022
Fcl-nuxt-starter - FCL plugin + full stack Nuxt application starter template

How to use the Flow Client Library (FCL) with Nuxt Access the FCL instance from

Bruno Gonzales 3 Jul 18, 2022
English-quiz-nuxt - An english quiz using nuxt

english-quiz-nuxt Live demo here Build Setup # install dependencies $ yarn insta

Leonid Gainar 2 Feb 17, 2022
Frisque-nuxt-storyblok - A basic framework for integrating StoryBlok with Nuxt

?? Frisque StoryBlok Welcome to the Frisque StoryBlok starter kit! This is curre

Sierra Layla Vithica 2 Feb 23, 2022
Netlify ❤️ Nuxt.js: a simple template to give you the code you need to use Netlify features with Nuxt.

Nuxt Toolbox Template This is a NuxtJS v2 project. It is a reference on how to integrate commonly used features within Netlify for Nuxt.js. Build Setu

null 19 Nov 7, 2022
A lightweight Nuxt template to build a Markdown driven website. Powered by Nuxt Content, TailwindCSS and Iconify.

A lightweight Nuxt template to build a Markdown driven website. Powered by Nuxt Content, TailwindCSS and Iconify.

Sébastien Chopin 470 Jan 2, 2023