react 國際化了解一下

背景

樓主最近新接了一個項目,從0開始作,須要作多語言的國際化,今天搞了一下,基本達到了想要的效果, 在這裏簡單分享下:html


一些探索

也說不上是探索吧,就Google了一波, GitHub 上找了一個比較成熟的庫 react-i18next, 寫了一些代碼,現將過程分享一下, 附帶詳細代碼,手把手教你實現國際化。node

先睹爲快

先看一下最後的成果:react

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

// xxx component
console.log('i18n來一發:', i18n.t('INVALID_ORDER'));

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

控制檯中:git

clipboard.png

對應json 中的信息:github

clipboard.png

開始

原理

原理其實很簡單: 字符串替換。web

拉取遠程的國際化json文件到本地,再根據語言作一個映射就能夠了。json

廢話很少說, 來看代碼吧。redux

先簡單看一下目錄結構:api

clipboard.png

先看一下 config 裏面的 相關代碼:react-router

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'
    ? 'your/transify/website/json/download'
    : `your/transify/website/${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 信息, 表示語言已經加載好了。

clipboard.png

在具體的業務組件中,使用方法是:

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

console.log('哈哈哈哈哈i18n來一發:', i18n.t('INVALID_ORDER'));

控制檯中:

clipboard.png

對應json 中的信息:

clipboard.png

後面你就能夠愉快的加各類詞條了。

Tips

咱們在src 中的文件中引入了src 目錄外的文件, 這是create-react-app 作的限制, 編譯會報錯, 把它去掉就行了:

clipboard.png

clipboard.png


關於多語言的設置

代碼示例:

i18next.init({
  lng: 'en',
});

初始化的時候能夠設置默認語言, 如須要切換系統語言, 能夠調用 i18n 提供的方法:

import { changeLanguage } from '@src/i18n';

// ...

  // 設置爲印尼語
  changeLanguage('id');

爲了保存語言設置, 能夠把 language 保存在 localStorage 中, 使用的時候直接從 storage 裏取。


結語

這裏做爲例, 就是把語言的json 文件下載下來放到locales 目錄裏, 若是想實時拉取,要保證文件下載完以後再render app.

相似:

loadResource(getLocale())
  .then(() => {
    import('./app.js')
  })


固然你也能夠免了這一步,直接下載好放到工程裏來。

大概就是這樣,以上就是實現國際化的所有代碼,但願對你們有所幫助。

相關文章
相關標籤/搜索