wisetc / practice

Practice conclusion
5 stars 0 forks source link

配置 create-react-app 架构的单页应用的提示文字 #38

Open wisetc opened 4 years ago

wisetc commented 4 years ago

通过设置 src/locale/locale.[SITE_ID].js 来添加 locale.

src/App.js

import { getSiteName } from 'src/locale'

const SITE_NAME = getSiteName()

src/locale/index.js

// locale/index.js
function loadLocale(id) {
  const ids = ['zhongtian'];
  if (!ids.includes(id)) {
    throw Error(`${id} is not one of ${ids.join(', ')}`);
  }

  return require(`./locale.${id}`);
}

let locale = null;

try {
  locale = loadLocale(window.SITE_ID).i18nLocale
} catch (error) {
  console.error(error)
}

export function getLabel(key) {
  if (locale === null) return undefined
  return locale[key]
}

export function getSiteName() {
  return getLabel('SITE_NAME')
}

src/locale/locale.zhongtian.js

// locale/locale.zhongtian.js
export const i18nLocale = {
  SITE_NAME: '中天',
}

public/index.html

<!-- public/index.html -->
  <head>
    <script>
      /** @typedef {'zhongtian'} SITE_ID */

      /** @type {SITE_ID} */
      var SITE_ID = '%REACT_APP_SITE_ID%';
    </script>
  </head>

script 脚本的位置应该放置于靠前的位置。

.env.local

REACT_APP_SITE_ID=zhongtian

可以通过环境变量 REACT_APP_SITE_ID 的设置来改变 window.SITE_ID 的值。