提交 74b99e24 编写于 作者: fxy060608's avatar fxy060608

wip(i18n): fallbackLocale

上级 856d6033
......@@ -3,15 +3,12 @@ import {
isServiceCustomElement,
} from '@dcloudio/uni-shared'
import { compileI18nJsonStr } from '@dcloudio/uni-i18n'
import {
UniVitePlugin,
initI18nOptions,
getFallbackLocale,
} from '@dcloudio/uni-cli-shared'
import { UniVitePlugin, initI18nOptions } from '@dcloudio/uni-cli-shared'
export function uniOptions(): UniVitePlugin['uni'] {
return {
copyOptions() {
const platfrom = process.env.UNI_PLATFORM
const inputDir = process.env.UNI_INPUT_DIR
const outputDir = process.env.UNI_OUTPUT_DIR
return {
......@@ -21,10 +18,7 @@ export function uniOptions(): UniVitePlugin['uni'] {
src: 'androidPrivacy.json',
dest: outputDir,
transform(source) {
const options = initI18nOptions(
inputDir,
getFallbackLocale(inputDir)
)
const options = initI18nOptions(platfrom, inputDir)
if (!options) {
return
}
......
import fs from 'fs'
import path from 'path'
import { I18N_JSON_DELIMITERS } from '@dcloudio/uni-shared'
import { I18N_JSON_DELIMITERS, once } from '@dcloudio/uni-shared'
import { parseJson, parseManifestJsonOnce } from './json'
import { M } from './messages'
export function initI18nOptions(inputDir: string, fallbackLocale?: string) {
const locales = initLocales(path.resolve(inputDir, 'locale'))
export function initI18nOptions(
platform: UniApp.PLATFORM,
inputDir: string,
warning: boolean = false,
withMessages: boolean = true
) {
const locales = initLocales(path.resolve(inputDir, 'locale'), withMessages)
if (!Object.keys(locales).length) {
return
}
const locale = normalizeI18nLocale(locales, fallbackLocale)
const manifestJson = parseManifestJsonOnce(inputDir)
const fallbackLocale = manifestJson.fallbackLocale || manifestJson.locale
const locale = resolveI18nLocale(
platform,
Object.keys(locales),
fallbackLocale
)
if (warning) {
if (!fallbackLocale) {
console.warn(M['i18n.fallbackLocale.missing'].replace('{locale}', locale))
} else if (locale !== fallbackLocale) {
console.warn(
M['i18n.fallbackLocale.unmatch'].replace('{locale}', fallbackLocale)
)
}
}
return {
locale,
locales,
......@@ -15,34 +37,44 @@ export function initI18nOptions(inputDir: string, fallbackLocale?: string) {
}
}
function initLocales(dir: string) {
export const initI18nOptionsOnce = once(initI18nOptions)
function initLocales(dir: string, withMessages: boolean = true) {
if (!fs.existsSync(dir)) {
return {}
}
return fs.readdirSync(dir).reduce((res, filename) => {
if (path.extname(filename) === '.json') {
try {
res[path.basename(filename).replace('.json', '')] = JSON.parse(
fs.readFileSync(path.join(dir, filename), 'utf8')
)
res[path.basename(filename).replace('.json', '')] = withMessages
? parseJson(fs.readFileSync(path.join(dir, filename), 'utf8'))
: {}
} catch (e) {}
}
return res
}, {} as Record<string, Record<string, string>>)
}
const defaultFallbackLocale = 'en'
// specifying locale > en > zh-Hans > zh-Hant > first locale
export function normalizeI18nLocale(
locales: Record<string, Record<string, string>>,
locale: string = defaultFallbackLocale
function resolveI18nLocale(
platfrom: UniApp.PLATFORM,
locales: string[],
locale?: string
) {
if (locales[locale]) {
if (locale && locales.includes(locale)) {
return locale
}
let defaultFallbackLocale = 'en'
const defaultLocales = ['zh-Hans', 'zh-Hant']
if (platfrom === 'app' || platfrom === 'h5') {
defaultLocales.unshift('en')
} else {
// 小程序
defaultLocales.push('en')
defaultFallbackLocale = 'zh-Hans'
}
return (
['en', 'zh-Hans', 'zh-Hant'].find((n) => locales[n]) ||
Object.keys(locales)[0] ||
defaultLocales.find((locale) => locales.includes(locale)) ||
locales[0] ||
defaultFallbackLocale
)
}
import { compileI18nJsonStr } from '@dcloudio/uni-i18n'
import { M } from '../../../messages'
import { initI18nOptions } from '../../../i18n'
export function initI18n(
manifestJson: Record<string, any>,
userManifestJson: Record<string, any>
) {
export function initI18n(manifestJson: Record<string, any>) {
const i18nOptions = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
userManifestJson.fallbackLocale
true
)
let fallbackLocale: string | undefined = undefined
if (i18nOptions) {
fallbackLocale = i18nOptions.locale
if (!userManifestJson.fallbackLocale) {
console.warn(
M['i18n.fallbackLocale.missing'].replace('{locale}', fallbackLocale)
)
} else if (userManifestJson.fallbackLocale !== fallbackLocale) {
console.warn(
M['i18n.fallbackLocale.unmatch'].replace(
'{locale}',
userManifestJson.fallbackLocale
)
)
}
if (manifestJson.plus.tabBar) {
manifestJson.plus.tabBar = JSON.parse(
compileI18nJsonStr(
......@@ -34,6 +17,6 @@ export function initI18n(
)
)
}
manifestJson.fallbackLocale = fallbackLocale
manifestJson.fallbackLocale = i18nOptions.locale
}
}
......@@ -33,7 +33,7 @@ export function normalizeAppManifestJson(
manifestJson,
pagesJson
)
initI18n(manifestJson, userManifestJson)
initI18n(manifestJson)
return manifestJson
}
......
......@@ -52,8 +52,3 @@ export function getUniStatistics(inputDir: string, platform: UniApp.PLATFORM) {
manifest[platform] && manifest[platform].uniStatistics
)
}
export function getFallbackLocale(inputDir: string) {
const manifest = parseManifestJsonOnce(inputDir)
return manifest.fallbackLocale
}
......@@ -2,18 +2,19 @@ export const M = {
'app.compiler.version': '编译器版本:{version}',
compiling: '正在编译中...',
'dev.performance':
'请注意运行模式下,因日志输出、sourcemap以及未压缩源码等原因,性能和包体积,均不及发行模式。',
'dev.performance.nvue': '尤其是app-nvue的sourcemap影响较大',
'dev.performance.mp': '若要正式发布,请点击发行菜单或使用cli发布命令进行发布',
'请注意运行模式下,因日志输出、sourcemap 以及未压缩源码等原因,性能和包体积,均不及发行模式。',
'dev.performance.nvue': '尤其是 app-nvue 的 sourcemap 影响较大',
'dev.performance.mp':
'若要正式发布,请点击发行菜单或使用 cli 发布命令进行发布',
'build.done': 'DONE Build complete.',
'dev.watching.start': '开始差量编译...',
'dev.watching.end': 'DONE Build complete. Watching for changes...',
'dev.watching.end.pages': 'DONE Build complete. PAGES:{pages}',
'dev.watching.end.files': 'DONE Build complete. FILES:{files}',
'stat.warn.appid':
'当前应用未配置Appid,无法使用uni统计,详情参考:https://ask.dcloud.net.cn/article/36303',
'当前应用未配置 appid,无法使用 uni 统计,详情参考:https://ask.dcloud.net.cn/article/36303',
'i18n.fallbackLocale.missing':
'当前应用未在manifest.json配置fallbackLocale,默认使用:{locale}',
'当前应用未在 manifest.json 配置 fallbackLocale,默认使用:{locale}',
'i18n.fallbackLocale.unmatch':
'当前应用配置的fallbackLocale为:{locale},但locale目录缺少该语言文件',
'当前应用配置的 fallbackLocale 或 locale 为:{locale},但 locale 目录缺少该语言文件',
}
......@@ -4,6 +4,7 @@ import {
defineUniManifestJsonPlugin,
normalizeNetworkTimeout,
parseJson,
initI18nOptions,
} from '@dcloudio/uni-cli-shared'
const defaultRouter = {
......@@ -52,6 +53,14 @@ export function uniManifestJsonPlugin(): Plugin {
let locale: string | null | undefined = manifest.locale
locale = locale && locale.toUpperCase() !== 'AUTO' ? locale : ''
const i18nOptions = initI18nOptions(
process.env.UNI_PLATFORM,
process.env.UNI_INPUT_DIR,
false,
false
)
const fallbackLocale = (i18nOptions && i18nOptions.locale) || ''
const flexDirection =
(manifest['app'] &&
manifest['app'].nvue &&
......@@ -71,6 +80,7 @@ export function uniManifestJsonPlugin(): Plugin {
export const qqMapKey = '${qqMapKey}'
export const sdkConfigs = ${JSON.stringify(sdkConfigs)}
export const locale = '${locale}'
export const fallbackLocale = '${fallbackLocale}'
`,
map: { mappings: '' },
}
......
......@@ -55,7 +55,7 @@ function generatePagesJsonCode(
return `
import { defineAsyncComponent, resolveComponent, createVNode, withCtx, openBlock, createBlock } from 'vue'
import { PageComponent, AsyncLoadingComponent, AsyncErrorComponent, useI18n, setupWindow } from '@dcloudio/uni-h5'
import { appid, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, nvue, locale } from '${manifestJsonPath}'
import { appid, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, nvue, locale, fallbackLocale } from '${manifestJsonPath}'
const locales = import.meta.globEager('./locale/*.json')
${importLayoutComponentsCode}
const extend = Object.assign
......@@ -261,6 +261,7 @@ delete ${globalName}['____'+appid+'____']
qqMapKey,
nvue,
locale,
fallbackLocale,
locales:Object.keys(locales).reduce((res,name)=>{res[name.replace(/\\.\\/locale\\/(.*).json/,'$1')]=locales[name].default;return res},{}),
router,
})
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册