原生js/Angular/Vue等不同框架下的中英文切换———多语言支持

近期研究了下不同框架下的中英文切换,本文主要用于总结。希望本文能对你项目多语言支持的技术选型有所帮助。

简介

框架i18n插件github地址描述证书
Angular@ngx-translate* https://github.com/ngx-translate/core * https://github.com/ngx-translate/http-loader * https://github.com/biesbjerg/ngx-translate-extractAngular 多语言支持插件MIT Licensed
Vuevue-i18nhttps://github.com/kazupon/vue-i18nVue多语言支持插件MIT Licensed
原生JSjquery-i18n-propertieshttps://github.com/jquery-i18n-properties/jquery-i18n-propertiesjquery.i18n.properties是一款轻量级的国际化插件,采用.properties文件来对javascript文件进行国际化,即根据用户指定的语言和国家编码来解析对应的以".properties"为后缀的文件。MIT Licensed
reactreact-intl

一、 jquery-i18n-properties

1. 依赖
2. 语言文件
  • Language.properties => Base properties
  • Language_zh.properties
  • Language_en.properties
3. 集成 jQuery-i18n-properties
  • 引入jQuery-i18n-properties
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script src="./js/jquery.i18n.properties.js"></script>
    <script src="./js/language.js"></script>
  • 准备 Language files
    在这里插入图片描述
  • 配置 language.js
    1. getNavLanguage
    2. config jQuery.i18n.properties()
let getNavLanguage = function () {
  if (navigator.appName == "Netscape") {
    let navLanguage = navigator.language;
    return navLanguage.substr(0, 2);
  }
  return false;
}


let execI18n = function () {
  let defaultLanguage = "zh";
  let locale = getNavLanguage();

  jQuery.i18n.properties({
    name: 'Messages',
    path: 'properties/',
    mode: 'both',
    language: locale || defaultLanguage,
    callback: function () {
      // init html by translated resources
      let insertEle = $(".i18n");
      insertEle.each(function () {
        $(this).html($.i18n.prop($(this).attr('name')));
      });

      // Accessing a simple value through a JS letiable
      alert(msg_hello + ' ' + msg_world);
      // Accessing a value with placeholders through a JS function
      alert(msg_complex('John', 'Monday'));
    }
  });
}

$(function () {
  execI18n();
});
4. 在html中使用相关的properties
 <div class="i18n" name="在language_files中定义的变量名"></div>
注意:需要使用Server加载语言文件,否则会出现跨域问题
5. 相关API
jQuery.i18n.properties()加载* .properties 资源文件
jQuery.i18n.prop()使用是资源文件中的值
jQuery.i18n.browserLang()获取浏览器语言
6. jQuery.i18n.properties()相关参数
选项描述类型可选
name资源文件的名称string [string]
language指定语言编码: (en: 英文, zh: 中文),或者同时指定语言编码和国家编码(例如: zh_CN, en_US)等string
path资源文件所在的路径string
mode加载模式: “vars”表示以javascript变量和函数的形式使用文件中的key,“map”表示以Map的方式使用文件中的key,“both”表示可以同时使用两种方式。如果资源文件中的key包含javascript中的关键字,只能使用map。默认值是vars。string
cache指定浏览器是否缓存资源文件,默认falseboolean
encoding指定加载资源文件时的编码格式,默认utf-8string
debug控制台是否记录记录logboolean
async指定调用callback(回调)函数的方式,false: 所有的资源文件加载请求发送完毕后就调用回调函数, true:所有的资源加载并解析完成后才调用回调函数。默认falseboolean
namespace指定资源文件的keys被存放在namespace下,即$.i18n.properties[namespace][key], 使用namespace可以最大限度的减少冲突和重写的概率; 默认为null不使用namespacestring
callback方法执行完的回调函数function

二、 vue-i18n

Vue I18n是Vue.js的国际化插件。它简单、强大且面向组件。
在这里插入图片描述

1. 引入vue-i18n
  • 对于没有使用@vue/cli的简单项目,可以在index.html中直接引入vue-i18n的CDN资源
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
 <script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
  • 对于使用@vue/cli的项目
npm install vue-i18n
 import Vue from 'vue'
 import VueI18n from 'vue-i18n'
 Vue.use(VueI18n)
2. 准备翻译文件

在这里插入图片描述

3. 创建VueI18n 实例

在这里插入图片描述

4. 在html文件中使用正确的vue-i18n注入方法

在这里插入图片描述

参考示例代码:
https://github.com/kazupon/vue-i18n/tree/dev/examples>
vue-i18n 教程:
http://kazupon.github.io/vue-i18n/guide/started.html
vue-i18n api
http://kazupon.github.io/vue-i18n/api/


三、 @ngx-translate

1. 安装@ngx-translate/core , @ngx-translate/http-loader
npm install @ngx-translate/core 
npm install @ngx-translate/http-loader
注意:一定要根据当前使用Angular的版本选择正确的@ngx-translate/core版本
Angular@ngx-translate/core@ngx-translate/http-loader
2 to 4.2.x7.x or less0.x
4.37.x or less1.x to 2.x
58.x to 9.x1.x to 2.x
610.x+3.x+
2. 在app.module.ts 中引入TranslateModule / TranslateLoader / TranslateHttpLoader
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export const TranslateLoaderFactory = (http: HttpClient) => {
	return new TranslateHttpLoader(http, './assets/i18n/','.json')
}
...
    imports: [
...
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: TranslateLoaderFactory,
                deps: [HttpClient]
            }
        }),
...
    ],
3. 定义翻译

en.json

{
    "HELLO": "hello"
}

zh.json

{
    "HELLO": "你好"
}
4. 初始化TranslateService
import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

@Component({
    selector: 'app',
    template: `
        <div>{{ 'HELLO' | translate }}</div>
    `
})
export class AppComponent {
    constructor(translate: TranslateService) {
        // this language will be used as a fallback when a translation isn't found in the current language
        const browserLang = translate.getBrowserLang();
        translate.setDefaultLang(browserLang);

         // the lang to use, if the lang isn't available, it will use the current loader to get them
        translate.use('en');
    }
}

参考教程
https://github.com/ngx-translate/core
参考示例
https://github.com/cassilup/angular-i18n-ngx-translate

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值