关于 javascript:在 i18n 中对同一语言环境使用两种语言代码

Using two language codes for same locale in i18n

我正在使用 i18n 来呈现翻译英语/日语 -- 我的默认语言是 en 中的英语。但最近意识到我的网站没有使用正确的日语 ISO 语言代码。 jp 而不是 ja.

我想知道是否有可能在 i18n 中让两种语言代码引用相同的语言环境文件——并且不知道如何做到这一点。

例如,我希望 /whatever?lng=jp/whatever?lng=ja 适用于日语文本。

这是我的配置:

i18nConfig.js

1
2
3
4
5
6
7
8
9
10
11
12
13
const path = require("path");

module.exports = {
  fallbackLng:"en",
  preload: ["en","ja","jp"],
  ns: [
   "localefiles"
  ],
  backend: {
    loadPath: path.join(__dirname,"locales","{{lng}}","{{ns}}.json"),
    addPath: path.join(__dirname,"locales","{{lng}}","{{ns}}.missing.json"),
  },
};

i18n.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const i18n = require("i18next");
const XHR = require("i18next-xhr-backend");
const LanguageDetector = require("i18next-browser-languagedetector");

const options = {
  fallbackLng:"en",
  load:"languageOnly",

  ns: ["common"],
  defaultNS:"common",

  debug: process.env.NODE_ENV !=="production" && false,
  saveMissing: true,

  interpolation: {
    escapeValue: false,
    formatSeparator:",",
    format: (value, format) => {
      if (format ==="uppercase") {
        return value.toUpperCase();
      }
      return value;
    },
  },
};

if (process.browser) {
  i18n.use(XHR).use(LanguageDetector);
}

if (!i18n.isInitialized) {
  i18n.init(options);
}

if (i18n.initialLanguage =="jp") {
  console.log({i18n})
  i18n.setLng("ja");
}

i18n.getInitialProps = (req, namespaces) => {
  if (!namespaces) {
    namespaces = i18n.options.defaultNS;
  }
  if (typeof namespaces ==="string") {
    namespaces = [namespaces];
  }

  req.i18n.toJSON = () => null;

  const initialI18nStore = {};
  req.i18n.languages.forEach((lan) => {
    initialI18nStore[lan] = {};
    namespaces.forEach((ns) => {
      initialI18nStore[lan][ns] = req.i18n.services.resourceStore.data[lan]
        ? req.i18n.services.resourceStore.data[lan][ns] || {}
        : {};
    });
  });
  return {
    i18n: req.i18n,
    initialI18nStore,
    initialLanguage: req.i18n.language,
  };
};

module.exports = i18n;

非常感谢您对这个基本问题的帮助。


您可以将 backend.loadPath 定义为获取 langs 的函数