近期在重構個人開源項目 iMap,想着要是能作成一個國際化的項目就行了,因而我在個人後端服務以及前端都引入了 i18njavascript
我用的是阿里系的 Egg.js Node 框架來提供後臺服務,因爲框架的開源插件中已經含有 egg-i18n,本着不重複造輪子的心態,因而直接上手。前端
首先打開 config/config.default.js
來設定 i18n 的配置項:vue
exports.i18n = { // 默認中文 defaultLocale: 'zh-CN', // // URL 參數,默認 'local' 改成 'lang' queryField: 'lang', // cookie 名稱 cookieField: 'lang', // cookie 時長 cookieMaxAge: '1y', };
其中,他們的彼此之間的權重是 query > cookie > headers
java
配置好 config
文件以後,須要在 config
文件夾中新增一個 local
文件夾,裏面放上項目的語言包,若是隻有中英文,那麼能夠是這樣的ios
. ├── config.default.js ├── config.local.js ├── config.prod.js ├── config.unittest.js ├── locale │ ├── en-US.js │ └── zh-CN.js └── plugin.js
固然也可使用 json
文件,詳情見 egg-i18n 文檔git
我爲了偷懶,直接使用了英文格式做爲 key
,像這樣github
// en-US module.exports = { // error_handler 'Not Found': 'Not Found', 'Authentication Error': 'Authentication Error', 'Server Error': 'Server Error', ... };
// zh-CN module.exports = { // error_handler 'Not Found': '錯誤 URL', 'Authentication Error': '權限錯誤', 'Server Error': '服務器錯誤', ... };
在項目中,例如咱們須要返回 Not Found
只須要使用 ctx.__('Not Found')
就能夠了,框架會自動根據當前請求語言來返回對應的預設語言包ajax
後端都集成了 i18n ,做爲老本行的前端固然也要配置,先看看效果vuex
本項目使用了 vue ,因此拿 vue 來進行舉例json
首先引入 vue-i18n
// main.js import Vue from 'vue' import VueI18n from 'vue-i18n' const i18n = new VueI18n({ // 默認中文 locale: 'zh-CN', messages: { // 語言包路徑 'zh-CN': require('@/common/lang/zh'), 'en-US': require('@/common/lang/en') } }) new Vue({ components: { App }, // 這裏別漏了 i18n, template: '<App/>' }).$mount('#app')
再在 common
文件夾中新建 lang
文件夾以及對應的語言包
# /src/common . └── lang ├── en.js └── zh.js
語言包內容示例
// en-US export const m = { login: { input_email: 'Please input email address', input_password: 'Please input password (4 - 25)', submit: 'Signin', github: 'Signin with ', reset: 'Lost your password ?', register: 'Signup now' },
// zh-CN export const m = { login: { input_email: '請輸入郵箱', input_password: '請輸入密碼(4 - 25位)', submit: '登陸', github: 'GitHub ', reset: '忘記密碼 ?', register: '當即註冊' }, }
這樣咱們就引入語言包成功,接下來是切換語言示例,在組件 methods
中使用 switchLang
方法
switchLang() { if (this.localLang === 'zh-CN') { this.localLang = 'en-US' } else { this.localLang = 'zh-CN' } // 切換語言 this.$i18n.locale = this.localLang // 使用 vuex 存入全局變量 this.setLang(this.localLang) },
在 template
中,使用 $t('m.你的key')
就能夠實現國際化了
可是如今還有一個問題,咱們如何在 script
標籤中使用 i18n 呢?
利用 this.$i18n.messages[this.$i18n.locale].m.你的key
就能夠作到
在咱們先後端都分別配置完成後,咱們須要前端是中文的時候,對應的後端返回的數據也是中文格式,在這裏,咱們利用 headers
中的 'Accept-Language'
來進行先後端的語言配對
axios
示例:
axios.post(obj.url, obj.data, { headers: { 'Accept-Language': window.$lang } })
這個 window.$lang
又是什麼呢...
爲了保證 ajax
配置文件的純淨簡潔(實際上是我懶)。爲了避免須要引入 i18n ,我在 vuex
中,將 this.$i18n.local
賦值給了 window
全局變量 $lang
// mutations const mutations = { // 設置 lang [types.SET_LANG] (state, data) { state.local = data window.$lang = data } }
這樣咱們就能夠很輕易的獲取到當前語言,從而傳給後端返回對應語言的數據
固然,爲了數據的持久化存儲,建議前端將當前語言配置存儲在 localstorage
或者是 cookie
裏面,不然刷新頁面將會遭到重置