fix: 🐛 修復 i18n 無法套用語言變體

修復 i18n 無法正確使用語言變體,轉而使用最靠近的語系翻譯
This commit is contained in:
noeFly
2025-02-12 21:29:18 +08:00
parent 1c2ba4942f
commit 8df49a195d
4 changed files with 23 additions and 36 deletions

View File

@@ -8,6 +8,7 @@ import zhCN from './lang/zh-CN'
import zhHK from './lang/zh-HK'
import zhTW from './lang/zh-TW'
import { extractLangPrefix } from './utils/pageId'
import { useRouter } from 'next/router'
/**
* 在这里配置所有支持的语言
@@ -70,15 +71,9 @@ export function generateLocaleDict(langString) {
*/
export function initLocale(locale, changeLang, updateLocale) {
if (isBrowser) {
// 根据router中的locale对象判断当前语言表现为前缀中包含 zh、en 等。
let pathLocaleLang = null
if (locale === 'en' || locale === 'zh') {
pathLocaleLang = locale === 'en' ? 'en-US' : 'zh-CN'
}
// 如果有query参数切换语言则优先
const queryLang =
getQueryVariable('locale') || getQueryVariable('lang') || pathLocaleLang
getQueryVariable('locale') || getQueryVariable('lang') || locale
if (queryLang) {
const match = queryLang.match(/[a-zA-Z]{2}(?:-[a-zA-Z]{2})?/)
if (match) {
@@ -91,22 +86,6 @@ export function initLocale(locale, changeLang, updateLocale) {
}
}
/**
* 读取语言
* @returns {*}
*/
export const loadLangFromLocalStorage = () => {
return localStorage.getItem('lang')
}
/**
* 保存语言
* @param newTheme
*/
export const saveLangToLocalStorage = lang => {
localStorage.setItem('lang', lang)
}
/**
* 检测用户的预研偏好,跳转至对应的多语言网站
* @param {*} lang
@@ -143,3 +122,13 @@ export const redirectUserLang = (lang, pageId) => {
}
}
}
/**
* 获取当前 Next.js 路由下的 locale
* @returns 当前路由下的 locale
*/
export function getCurrentLang() {
const router = useRouter()
let currentLang = router.locale
return currentLang
}