如何处理带参数的翻译字符串(如 'Hello, {name}!')?

解读

在国内一线/二线大厂的 Svelte 面试中,这道题考察的不是“能不能把变量塞进字符串”,而是“能否在零运行时成本的前提下,把 i18n 做成编译期可优化、可静态抽取、可回滚、可 SSR 同构的完整方案”。
面试官通常会给一个追加限制:

  1. 不能引入 runtime i18n 框架(如 i18next),因为与 Svelte“零运行时”理念冲突;
  2. 必须支持参数插值、复数、性别、货币等 ICU 语法;
  3. 必须让翻译文件走 CDN 缓存,且支持灰度回滚;
  4. 必须保证 Lighthouse i18n 审计 100 分,SEO 不降级。
    如果候选人只回答“用模板字符串”或“用 {$_('key', {name})}”,会被追问性能、代码分割、缓存策略、SEO、灰度方案,直至答出编译期静态抽取与 SSR 注入为止。

知识点

  1. Svelte 编译期宏:svelte-preprocess 自定义宏,在 compile 阶段把翻译标记转成静态 import。
  2. ICU MessageFormat:支持 {name}、{count, plural, …}、{gender, select, …},需用轻量级实现(messageformat 仅 2 kB gzip)。
  3. 静态抽取 & 代码分割:vite-plugin-svelte-i18n 在 build 阶段扫描所有 $tkey 模板字面量,生成 lang.{locale}.chunk.{hash}.js,走 CDN 长期缓存。
  4. SSR 注入:server 端根据 accept-language + 灰度版本,把对应 lang chunk 内联进 SVELTE_I18N 全局,hydrate 时直接复用,避免 FOIT。
  5. 响应式更新:用 Svelte 可读 store 保存当前 locale,切换语言时动态 import 新 chunk,触发顶层 $locale.set(),下游组件自动重新渲染,无需手动 key 刷新。
  6. 类型安全:通过 TypeScript 声明合并,让 $t 函数返回字面量联合类型,写错 key 直接编译失败,杜绝线上 404 翻译。
  7. 灰度 & 回滚:翻译文件走 OSS + 版本号目录,nginx 根据 header x-i18n-version 转发,回滚只需改目录软链,无需重新发版。
  8. 性能指标:通过编译期静态化,使带参数字符串在 runtime 仅做一次 JSON.parse + 一次 replace,CPU 耗时 < 0.1 ms,LCP 零影响。

答案

  1. 项目结构
    src/lib/i18n/index.ts
    src/locales/en.json
    src/locales/zh-CN.json

  2. 编译期宏(svelte-preprocess)

// src/lib/i18n/macro.js
export default function i18nMacro() {
  return {
    markup: ({ content, filename }) => {
      return content.replace(/\$t`([^`]+)`/g, (_, key) => {
        return `{@html $_(${JSON.stringify(key)}, $$props)}`;
      });
    }
  };
}
  1. 轻量 ICU 实现
// src/lib/i18n/icu.ts
import MessageFormat from '@messageformat/core';
const cache = new Map<string, MessageFormat>();
export const compile = (msg: string) => {
  if (!cache.has(msg)) cache.set(msg, new MessageFormat(msg));
  return cache.get(msg);
};
  1. 可读 store
// src/lib/i18n/store.ts
import { readable } from 'svelte/store';
import { compile } from './icu';

export const locale = readable('zh-CN', set => {
  // 服务端注入初始值
  if (typeof window === 'undefined') return;
  const initial = window.__SVELTE_I18N__.locale;
  set(initial);
});

export function $(key: string, params?: Record<string, any>) {
  const messages = (typeof window === 'undefined'
    ? global.__SVELTE_I18N__.messages
    : window.__SVELTE_I18N__.messages) || {};
  const msg = messages[key] || key;
  return compile(msg)(params);
}
  1. 组件内使用
<script lang="ts">
  import { $ } from '$lib/i18n';
  export let name: string;
</script>

<p>{$('hello', { name })}</p>
<!-- 编译后等价于 <p>{@html $_('hello', { name })}</p> -->
  1. vite 插件做静态抽取 & 代码分割
// vite-plugin-svelte-i18n.ts
export default function vitePluginSvelteI18n() {
  const keys = new Set<string>();
  return {
    name: 'svelte-i18n',
    transform(code, id) {
      if (!id.includes('src')) return;
      const matches = code.matchAll(/\$t`([^`]+)`/g);
      for (const [, key] of matches) keys.add(key);
    },
    generateBundle(options, bundle) {
      const locales = ['en', 'zh-CN'];
      locales.forEach(locale => {
        const data = Object.fromEntries(
          [...keys].map(k => [k, require(`../locales/${locale}.json`)[k]])
        );
        this.emitFile({
          type: 'chunk',
          id: `virtual:i18n-${locale}`,
          fileName: `lang.${locale}.[hash].js`,
          facadeModuleId: `virtual:i18n-${locale}`
        });
      });
    }
  };
}
  1. SSR 注入(SvelteKit hook)
// src/hooks.ts
export async function handle({ event, resolve }) {
  const locale = event.request.headers.get('accept-language')?.split(',')[0] || 'zh-CN';
  const chunk = await import(`$lib/i18n/lang.${locale}.chunk.js`);
  return resolve(event, {
    transformPageChunk: ({ html }) =>
      html.replace(
        '<head>',
        `<head><script>window.__SVELTE_I18N__=${JSON.stringify({
          locale,
          messages: chunk.default
        })}</script>`
      )
  });
}
  1. 灰度 & 回滚
    翻译文件上传至 https://cdn.example.com/i18n/v1.2.3/zh-CN.chunk.js,nginx 根据 x-i18n-version: v1.2.3 转发;回滚时把软链指回 v1.2.2 即可。

拓展思考

  1. 微前端场景:子应用独立部署,如何共享主应用语言包?
    方案:主应用通过 import-map 把 lang.*.chunk.js 注入到 window.System,子应用用 System.import 获取,保证只加载一次,避免重复拆包。

  2. 编译期 Tree-Shaking:如果某个 key 只在 A/B 实验分支用到,如何让生产包剔除?
    方案:在 vite 插件里读 process.env.FEATURES,未启用的实验 key 不写入 chunk,配合 rollup 的 manualChunks 做条件拆包。

  3. 前端灰度与后端不一致:用户前端版本 v1.2.3,后端返回 v1.2.2 翻译,导致 key 缺失。
    方案:在 SSR 阶段对比前后版本号,若不一致,降级到后端版本,同时上报 Sentry,触发 CDN 预热,10 分钟内对齐。

  4. 性能极限:WebAssembly 版 ICU4X 可把编译后 msg 体积再降 30%,但增加 80 kB wasm,取舍点在于项目是否面向海外低端安卓机;可在 vite 插件里根据 User-Agent 动态选择 wasm 或 js 版本。