Express使用i18n实现多语言

362 阅读1分钟

为什么要用express,我是一名前端开发,现在是一名独立开发者,主打的就是一个人全搞定,要快,所以就用express上了。

image.png

依赖

i18n
express
cookie-parser

入口

const express = require('express')
const cookieParser = require('cookie-parser')
const app = express()
app.use(cookieParser())
// i18n
i18n.configure({
  //zh中文 en英文 sun日语 han韩语
  locales: ['zh', 'en', 'sun', 'han'], // 声明包含语言
  directory: __dirname + '/lang', // 设置语言文件目录
  cookie: 'lang',
  defaultLocale: 'zh' // 设置默认语言
})
app.use(i18n.init)

多语言文件夹lang

lang 
    en.json
    han.json
    sun.json
    zh.json

en.json

{
  "test": "Test"
}

zh.json

{
  "test": "测试"
}

使用

测试一下是不是能正常切换

router.post('/', function (req, res, next) {
  console.log(res.__('test'), '====')
}

image.png

前端部分

使用的是vue-i18n,具体的vue-i18n的使用就不写了,只写一下怎么存的cookie

import Cookies from 'js-cookie'

//选择了语言的时候存一下cookie
function setLang(key){
  Cookies.set('lang', key,{ secure: true })
}

效果

image.png

image.png