欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

react 国际化的实现代码示例

程序员文章站 2022-03-22 11:36:55
背景 楼主最近新接了一个项目,从0开始做,需要做多语言的国际化,今天搞了一下,基本达到了想要的效果, 在这里简单分享下: 一些探索 也说不上是探索吧,就google了...

背景

楼主最近新接了一个项目,从0开始做,需要做多语言的国际化,今天搞了一下,基本达到了想要的效果, 在这里简单分享下:

一些探索

也说不上是探索吧,就google了一波, 去gayhub 上找了一个比较成熟的库 react-i18next, 写了一些代码,现将过程分享一下, 附带详细代码,手把手教你实现国际化。

先睹为快

先看一下最后的成果:

 // ...
import i18n from '@src/i18n';


// xxx component

 console.log('哈哈哈哈哈i18n来一发:', i18n.t('invalid_order'));

// ...
render() { 
 // ...
 <button> {i18n.t('invalid_order')} <button>
}

控制台中:

react 国际化的实现代码示例

对应json 中的信息:

react 国际化的实现代码示例

开始

原理

原理其实很简单: 字符串替换。

拉取远程的国际化json文件到本地,再根据语言做一个映射就可以了。

废话不多说, 来看代码吧。

先简单看一下目录结构:

react 国际化的实现代码示例

先看一下 config 里面的 相关代码:

env.js:

'use strict';

const fs = require('fs');
const path = require('path');
const paths = require('./paths');
const languages = require('./languages');

// make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];

const node_env = process.env.node_env;
if (!node_env) {
 throw new error(
  'the node_env environment variable is required but was not specified.'
 );
}

// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
var dotenvfiles = [
 `${paths.dotenv}.${node_env}.local`,
 `${paths.dotenv}.${node_env}`,
 // don't include `.env.local` for `test` environment
 // since normally you expect tests to produce the same
 // results for everyone
 node_env !== 'test' && `${paths.dotenv}.local`,
 paths.dotenv,
].filter(boolean);

// load environment variables from .env* files. suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set. variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
dotenvfiles.foreach(dotenvfile => {
 if (fs.existssync(dotenvfile)) {
  require('dotenv-expand')(
   require('dotenv').config({
    path: dotenvfile,
   })
  );
 }
});

// we support resolving modules according to `node_path`.
// this lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.
// it works similar to `node_path` in node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// note that unlike in node, only *relative* paths from `node_path` are honored.
// otherwise, we risk importing node.js core modules into an app instead of webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
// we also resolve them to make sure all tools using them work consistently.
const appdirectory = fs.realpathsync(process.cwd());
process.env.node_path = (process.env.node_path || '')
 .split(path.delimiter)
 .filter(folder => folder && !path.isabsolute(folder))
 .map(folder => path.resolve(appdirectory, folder))
 .join(path.delimiter);

// grab node_env and react_app_* environment variables and prepare them to be
// injected into the application via defineplugin in webpack configuration.
const react_app = /^react_app_/i;

function getclientenvironment(publicurl) {
 const raw = object.keys(process.env)
  .filter(key => react_app.test(key))
  .reduce(
   (env, key) => {
    env[key] = process.env[key];
    return env;
   },
   {
    // useful for determining whether we're running in production mode.
    // most importantly, it switches react into the correct mode.
    node_env: process.env.node_env || 'development',
    // useful for resolving the correct path to static assets in `public`.
    // for example, <img src={process.env.public_url + '/img/logo.png'} />.
    // this should only be used as an escape hatch. normally you would put
    // images into the `src` and `import` them in code to get their paths.
    public_url: publicurl,
    language: {
     resources: languages.resources,
     defaultlng: languages.defaultlng
    },
    country: process.env.country
   }
  );
 // stringify all values so we can feed into webpack defineplugin
 const stringified = {
  'process.env': object.keys(raw).reduce((env, key) => {
   env[key] = json.stringify(raw[key]);
   return env;
  }, {}),
 };

 return { raw, stringified };
}

module.exports = getclientenvironment;

主要看lannguage 相关的代码就好了, 其他的都create-react-app 的相关配置, 不用管。

再看下 language.js 里面的逻辑:

const path = require('path');
const paths = require('./paths');
const localeshash = require('../i18n/localeshash');
const resourceshash = require('../i18n/resourceshash');

const country = process.env.country || 'sg';
const country = (country).touppercase();
const defaultlng = localeshash[country][0];

const langs = [
 'en',
 'id'
];

const prefixlangs = [];
const entries = {};

for (let i = 0, len = langs.length; i < len; i++) {
 const prefixlang = `dict_${langs[i]}`
 prefixlangs.push(prefixlang)
 entries[prefixlang] = path.resolve(paths.appsrc, `../i18n/locales/${langs[i]}.json`)
}

const resources = {
 [defaultlng]: {
  common: resourceshash[defaultlng]
 }
}

exports.resources = resources;
exports.defaultlng = defaultlng;

逻辑也比较简单, 根据语言列表把对应的json 内容加进来。 作为示例,这里我设置的是 英文 和 印尼语。

下面看 i18n 文件里面的内容:

locales 里面放的是语言的json 文件, 内容大概是:

{
  "msg_created": "pesanan telah terbuat"
  // ...
}

localeshash.js:

module.exports = {
 sg: ['en'],
 id: ['id']
}

resourceshash.js:

module.exports = {
 'en': require('./locales/en.json'),
 'id': require('./locales/id.json')
}

index.js

const path = require('path')
const fs = require('fs')
const fetch = require('isomorphic-fetch')
const localeshash = require('./localeshash')

const argv = process.argv.slice(2)
const country = (argv[0] || '').touppercase()

const i18nserveruri = locale => {
 const keywords = {
  'en': 'en',
  'id': 'id'
 }
 const keyword = keywords[locale]
 return keyword === 'en'
  ? 'xxx/json/download'
  : `/${keyword}/json/download`
}

const fetchkeys = async (locale) => {
 const uri = i18nserveruri(locale)
 console.log(`downloading ${locale} keys...\n${uri}`)
 const respones = await fetch(uri)
 const keys = await respones.json()
 return keys
}

const access = async (filepath) => {
 return new promise((resolve, reject) => {
  fs.access(filepath, (err) => {
   if (err) {
    if (err.code === 'exist') {
     resolve(true)
    }
    resolve(false)
   }
   resolve(true)
  })
 })
}

const run = async () => {
 const locales = localeshash[country] || object
  .values(localeshash)
  .reduce(
   (previous, current) =>
    previous.concat(current), []
  )
 if (locales === undefined) {
  console.error('this country is not in service.')
  return
 }
 for (const locale of locales) {
  const keys = await fetchkeys(locale)
  const data = json.stringify(keys, null, 2)
  const directorypath = path.resolve(__dirname, 'locales')
  if (!fs.existssync(directorypath)) {
   fs.mkdirsync(directorypath)
  }
  const filepath = path.resolve(__dirname, `locales/${locale}.json`)
  const isexist = await access(filepath)
  const operation = isexist ? 'update' : 'create'
  console.log(operation)
  fs.writefilesync(filepath, `${data}\n`)
  console.log(`${operation}\t${filepath}`)
 }
}

run();

再看下src 中的配置:

i18nn.js

import i18next from 'i18next'
import { firstletterupper } from './common/helpers/util';
const env = process.env;
let language = process.env.language;
language = typeof language === 'string' ? json.parse(language) : language

const { defaultlng, resources } = language

i18next
 .init({
  lng: defaultlng,
  fallbacklng: defaultlng,
  defaultns: 'common',
  keyseparator: false,
  debug: env.node_env === 'development',
  resources,
  interpolation: {
   escapevalue: false
  },
  react: {
   wait: false,
   bindi18n: 'languagechanged loaded',
   bindstore: 'added removed',
   nsmode: 'default'
  }
 })

function ismatch(str, substr) {
 return str.indexof(substr) > -1 || str.tolowercase().indexof(substr) > -1
}

export const changelanguage = (locale) => {
 i18next.changelanguage(locale)
}

// uppercase the first letter of every word. abcd => abcd or abcd efg => abcd efg
export const tupper = (str, allwords = true) => {
 return firstletterupper(i18next.t(str), allwords)
}

// uppercase all letters. abcd => abcd
export const tuppercase = (str) => {
 return i18next.t(str).touppercase()
}

export const loadresource = lng => {
 let p;

 return new promise((resolve, reject) => {
  if (ismatch(defaultlng, lng)) resolve()

  switch (lng) {
   case 'id':
    p = import('../i18n/locales/id.json')
    break
   default:
    p = import('../i18n/locales/en.json')
  }

  p.then(data => {
   i18next.addresourcebundle(lng, 'common', data)
   changelanguage(lng)
  })
   .then(resolve)
   .catch(reject)
 })
}

export default i18next
 // firstletterupper

export const firstletterupper = (str, allwords = true) => {
 let tmp = str.replace(/^(.)/g, $1 => $1.touppercase())
 if (allwords) {
  tmp = tmp.replace(/\s(.)/g, $1 => $1.touppercase())
 }
 return tmp;
}

这些准备工作做好后, 还需要把i18n 注入到app中:

index.js:

import react from 'react';
import { render } from 'react-dom';
import { provider } from 'react-redux';
import rootreducer from './common/redux/reducers';
import { configurestore } from './common/redux/store';
import { router } from 'react-router-dom';
import createbrowserhistory from 'history/createbrowserhistory';
import { i18nextprovider } from 'react-i18next';
import i18n from './i18n';
import './common/styles/index.less';
import app from './app';
export const history = createbrowserhistory();

const root = document.getelementbyid('root');

render(
 <i18nextprovider i18n={i18n}>
  <provider store={configurestore(rootreducer)} >
   <router history={history}>
    <app />
   </router>
  </provider>
 </i18nextprovider>,
 root
);

如何使用

加入上面的代码后, 控制台会有一些log 信息, 表示语言已经加载好了。

react 国际化的实现代码示例

在具体的业务组件中,使用方法是:

 // ...
import i18n from '@src/i18n';

console.log('哈哈哈哈哈i18n来一发:', i18n.t('invalid_order'));

控制台中:

react 国际化的实现代码示例

对应json 中的信息:

react 国际化的实现代码示例

后面你就可以愉快的加各种词条了。

tips

我们在src 中的文件中引入了src 目录外的文件, 这是create-react-app 做的限制, 编译会报错, 把它去掉就好了:

react 国际化的实现代码示例

react 国际化的实现代码示例

结语

这里作为例, 就是把语言的json 文件下载下来放到locales 目录里, 如果想实时拉取,要保证文件下载完之后再render app.

类似:

loadresource(getlocale())
 .then(() => {
  import('./app.js')
 })

当然你也可以免了这一步,直接下载好放到工程里来。

大概就是这样,以上就是实现国际化的全部代码,希望对大家有所帮助。也希望大家多多支持。