当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解基于webpack&gettext的前端多语言方案

详解基于webpack&gettext的前端多语言方案

2019年03月17日  | 移动技术网IT编程  | 我要评论

gettext 是gnu 提供的一套 国际化与本地化 处理的相关函数库。大多数语言都有对应的gettext实现。本文主要使用来实现gettext 一系列方法对应的功能。

pot/po文件

  • pot文件 是po文件的模板文件,一般是通过 xgettext 程序生成出来的。
  • po文件 是根据pot文件通过msginit程序,设置对应的国家语言生成用于填写实际翻译内容的文件。

xgettext/msginit/msgmerge

  • xgettext 程序可以扫描指定的代码文件,取出其中gettext部分的内容生成对应的pot文件。
  • msginit 根据对应的pot文件生成对应语言版本用于实际翻译的po文件。
  • msgmerge 如果对应语言版本的po文件存在的话,则需要使用msgmerge方式把pot文件中新加入的一些msgid合并到po文件当中。

多语言支持流程

安装gettext

brew install gettext
brew link gettext

langs-loader 加载语言文件

  • 安装
npm install git@github.com:ezbuy/langs-loader.git --save-dev
  • 配置

需要修改webpack.config.js文件在module->rules(webpack 2.0)下面添加loader规则:

{
  test: /\.pot$/i,
  use: [
    "json",
    {
      loader: 'langs',
      options: {isloadall: isdev,format:"jed1.x", "fallback-to-msgid":true, code:langcode}
    }
  ]
}

  • isloadall

isloadall表示会把所有语言版本的文件通过po2json转换成json,然后组合成一个json作为数据传给引用的地方。

  • code

code选项一般需要在代码发布时指定,不同语言版本打包时通过传入不同的code区分不同语言版本的代码打包。

代码中使用gettext系列函数

各端开发时使用各自实现的gettext方法去包装需要实现多语言的文案。使用gettext函数包装后, langs-util 就能知道代码中有需要多语言翻译的地方,并可以通过 langs-util 生成相关的pot及po文件。gettext方法底层我们使用来实现其对应功能。

import toi18n from "common/i18n";

const _ = toi18n(require("langs/index.pot"));

const histr = _.gettext("hi!");

const num = math.ceil(math.random() * 2);

const numstr = _.ngettext("item", "items", num);

// i like your red shirt.
console.log(_.sprintf( "i like your %1$s %2$s.", 'red', 'shirt'));
  • gettext

一般使用 gettext 方法包装一个需要翻译的字符串。

  • ngettext

可以用于单复数处理,第一个参数传入单数情况下的翻译,第二个参数传入复数情况下的翻译,第三个传入实际需要执行判断的数据。

  • sprintf

jed内置提供了sprintf的支持,它是使用的sprintf函数的实现。

通过gettext 一系列函数的配合,使用 langs-util 进行生成处理后就能生成对应的pot及po文件。

langs-util gen -i src/
# langs/index.pot

msgid "hi!"
msgstr ""

msgid "item"
msgid_plural "items"
msgstr[0] ""
msgstr[1] ""
# langs/index.th.po

msgid "hi"
msgstr ""

msgid "item"
msgid_plural "items"
msgstr[0] ""
msgstr[1] ""

把生成的文件交由对应的翻译人员完成翻译就可以重新放回到文件夹当中替换目标po文件。

打包&发布

各端打包方式都会有相应的差异,最终目的无非就是使线上代码可以按照不同语言的版本加载不同的语言文件。对于 后台 等系统则可以使用isloadall的方式把所有语言版本的文件都加载进来,通过i18n的包装函数去从数据源中拿出不同国家的多语言数据文件。

cross-env lang_code=th

移动端发布使用环境变量 lang_code 来区分要编译成的语言版本。

const langcode = process.env.lang_code

{
  test: /\.pot$/i,
  use: [
    "json",
    {
      loader: 'langs',
      options: {isloadall: isdev,format:"jed1.x", "fallback-to-msgid":true, code:langcode}
    }
  ]
}

生成完所有语言语言版本的静态文件后,需要让浏览器能够运行不同语言版本的js文件。一种方式可以通过后台程序读出语言版本,再把正确语言版本的js路径输出到html当中。另外一种方式可以新建一个多语言loader的文件,通过前端js代码动态插入正确语言版本的js代码(文件打包的时候需要把各语言版本的js文件路径输出到页面之中)。

import {languagecode} from "common/constant";

const loadscript = (path: string) => {
  const script = window.document.createelement("script");
  script.setattribute("src", path);
  window.document.body.appendchild(script);
  return new promise((resolve, reject) => {
    script.onload = resolve;
    script.onerror = reject;
  });
};

const {mainfilepath} = window;

if (typeof mainfilepath === "string") {
  loadscript(mainfilepath);
}else if (typeof mainfilepath !== "string") {
  loadscript(mainfilepath[languagecode] );
}

langs-loader 实现

在loader代码中拿到require文件的实际路径,如果存在code选项的话则根据pot文件找到对应code的po文件,然后使用po2json转换为对应格式的json文件,最后再返回给引用的地方。如果存在isloadall选项并且isloadall选项为true的话,则会load 同名pot文件的所有对应语言版本的po文件,然后再通过po2json转换组合成一个json文件,再返回出去。

langs-util 实现

langs-util主要整合了xgettext/msginit/msgmerge等方法。传入所需要解析的文件或文件夹,生成对应的po及pot文件。

const genpofiles = (inputfilepaths: string | string[], potfilepath: string, langs: string[]) => {
  const potdirname = dirname(potfilepath);
  const filename = basename(potfilepath, extname(potfilepath));
  const filepaths = typeof inputfilepaths === "string" ? inputfilepaths : inputfilepaths.join(" ");
  execonlyerroroutput(`xgettext --language=javascript --add-comments --sort-output --from-code=utf-8 --no-location --msgid-bugs-address=wanglin@ezbuy.com -o ${potfilepath} ${filepaths}`);

  checkfileexists(potfilepath).then((ifpotfileexists) => {
    if (ifpotfileexists) {
      console.log(green(potfilepath));
      writefilesync(potfilepath, readfilesync(potfilepath).tostring().replace("charset=charset", "charset=utf-8"));
      langs.foreach((lang) => {
        const pofilepath = join(potdirname, `${filename}${lang === "" ? "" : `.${lang}` }.po`);
        checkfileexists(pofilepath).then((ifexists) => {
          if (ifexists) {
            execonlyerroroutput(`msgmerge --output-file=${pofilepath} ${pofilepath} ${potfilepath}`);
          }else {
            execonlyerroroutput(`msginit --no-translator --input=${potfilepath} --locale=${lang} --output=${pofilepath}`);
          }
        });
      });
    }
  });
};

生成po文件时,需要传入需要给xgettext解析的文件列表以及目标pot文件路径还有生成的多语言版本种类。xgettext会根据传入的解析文件生成新的pot文件,如果生成成功则开始生成对应语言版本的po文件,如果对应的po文件存在则使用msgmerge更新po文件,如果不存在则使用msginit创建新的po文件。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网