i18n API

Vue API 来自 ubean/client(可自动导入)。Handler API 来自 ubean/i18n(@ubean/i18n)。

Vue — ubean/client

API说明
useI18n()vue-i18n Composition API(t / d / n / tm / locale / …),直接从 vue-i18n 导入
setLocale(code)加载文案、写 cookie、router.replace(switchLocalePath)
useLocalePath()(path, locale?) => 本地化路径
useSwitchLocalePath()(locale) => 当前路由在目标语言下的路径
useLocaleRoute()useLocalePath 别名
useLocaleHead()响应式 hreflang / canonical / og:locale
getI18nRuntimeConfig()解析后的 { defaultLocale, locales, strategy, … }
<Link locale="zh">按指定 locale 本地化 to
<script setup lang="ts">
const { t, locale } = useI18n();
const localePath = useLocalePath();

await setLocale('zh');
</script>

不要把 locale.value = x 当公共切换 API。客户端 useI18n 直接从 vue-i18n 导入(或经自动导入)。

服务端 — ubean/i18n

API说明
t(key, …) / d() / n()在请求 ALS 内翻译 / 格式化
runWithI18n(scope, fn)在 ALS 作用域内执行(测试 / 内部)
getRequestLocale(c)自动中间件写入的 locale(c.get('locale'))
compileLocalePaths(path, cfg)vue / Hono 共用路径编译器
localizePath / switchLocalePath / extractLocaleFromPath纯路径工具
createI18nMiddleware(options)由 createUbeanApp 调用,一般不必手写
buildLocaleHead(input)hreflang / canonical / og:locale
setLocaleMessages / getLocaleMessages@intlify/core 使用的文案表

t() 在 ALS 外 抛错,没有进程全局 locale。

import { defineHandler } from 'ubean/server';
import { t, getRequestLocale } from 'ubean/i18n';

export const GET = defineHandler(c => {
  return c.json({ locale: getRequestLocale(c), msg: t('hello') });
});

配置(ubean.config.ts)

i18n: false | {
  defaultLocale?: string;
  locales?: Array<string | {
    code: string;
    language?: string;
    name?: string;
    dir?: 'ltr' | 'rtl';
    files?: string[];
  }>;
  strategy?: 'prefix' | 'prefix_except_default' | 'prefix_and_default' | 'no_prefix';
  baseUrl?: string;
  detectBrowserLanguage?: false | {
    cookieName?: string;
    redirectOn?: 'root' | 'all';
    alwaysRedirect?: boolean;
  };
  vueI18n?: {
    fallbackLocale?: string;
    fallbackWarn?: boolean;
    missingWarn?: boolean;
    datetimeFormats?: object;
    numberFormats?: object;
  };
}

默认:strategy: 'prefix_except_default',detectBrowserLanguage.redirectOn: 'root'。中间件自动挂载。

类型

.ubean/i18n.d.ts 根据默认 locale JSON 增强 vue-i18n 的 DefineLocaleMessage,使 t('missing') 类型检查失败。请在 tsconfig.json 中包含 .ubean/*.d.ts(脚手架默认已包含)。

已删除(无兼容层):defineLocale、addLocale、mergeLocale、clearLocales、formatDate / formatNumber / formatCurrency / formatRelativeTime / formatList,以及 @ubean/i18n 的进程级 useI18n()。请改用 vue-i18n 的 d / n 和 ALS t()。