Paraglide JS

使用 SSG 时,本地化页面在构建时生成,而不是在每次请求时生成。因此,你需要告诉框架要生成哪些语言区域变体,并在每个页面渲染前显式设置语言区域。

[!IMPORTANT]SSG 不使用 paraglideMiddleware(),因为没有需要处理的请求。你必须在构建期间通过 setLocale() 或 overwriteGetLocale() 以编程方式设置语言区域。

  • setLocale() - 适用于同步构建,页面逐个渲染
  • overwriteGetLocale() - 适用于并发渲染(React),多个页面可能同时构建

为什么必须显式设置语言区域

在 SSR 中,中间件会从传入请求的 URL 中提取语言区域。而 SSG 中不存在请求——页面是在构建时渲染的。由于没有浏览器,Paraglide 运行时无法读取 window.location。因此,你必须在渲染每个页面之前告诉 Paraglide 要使用哪个语言区域。

[!NOTE] SSG 通常要求所有语言区域都带 URL 前缀(例如 /en/about、/de/about),这样每个语言区域才能各自生成独立的静态文件。在 SSR 中,/about 可以动态提供不同语言区域的内容;而 SSG 则需要不同的文件路径。请参阅下方的 URL 配置。

页面发现

框架需要知道为每个语言区域生成哪些页面。使用 generateStaticLocalizedUrls() 从你的模式中获取所有本地化 URL:

import { generateStaticLocalizedUrls } from "./paraglide/runtime.js";

const localizedUrls = generateStaticLocalizedUrls([
  "/",
  "/about",
  "/blog",
  "/blog/post-1",
  "/blog/post-2",
]);

console.log(localizedUrls);
// [
//   "/en/", "/de/",
//   "/en/about", "/de/about",
//   "/en/blog", "/de/blog",
//   "/en/blog/post-1", "/de/blog/post-1",
//   "/en/blog/post-2", "/de/blog/post-2"
// ]

这同样适用于生成站点地图和 <link rel="alternate" hreflang> 标签。

框架示例

SvelteKit (entries)

通过 entries 导出告诉 SvelteKit 要预渲染哪些页面。本示例使用必需的 [locale] 参数 (所有页面都带有语言区域前缀,例如 /en/about) :

src/routes/
  [locale]/
    +page.svelte
    +page.ts
    about/
      +page.svelte
// src/routes/[locale]/+page.ts
import { locales } from "$paraglide/runtime.js";

export const prerender = true;

export function entries() {
  return locales.map((locale) => ({ locale }));
}

对于动态路由,需要列出所有语言区域与 slug 的组合:

// src/routes/[locale]/blog/[slug]/+page.ts
import { locales } from "$paraglide/runtime.js";

export const prerender = true;

export async function entries() {
  const posts = await getPosts(); // 你自己的数据获取逻辑

  // 生成所有 locale + slug 组合
  return locales.flatMap((locale) =>
    posts.map((post) => ({ locale, slug: post.slug }))
  );
}

Next.js (generateStaticParams)

// app/[locale]/page.tsx
import { locales } from "@/paraglide/runtime.js";

export function generateStaticParams() {
  return locales.map((locale) => ({ locale }));
}

[!TIP]在 tsconfig.json 中配置 @/paraglide 这类路径别名,避免使用容易出错的相对路径导入。

Astro (getStaticPaths)

Astro 仅在静态路由或预渲染路由中使用 getStaticPaths()。如果你的 Astro 项目使用 output: "server" 并搭配 Paraglide 的服务端中间件,那么除非页面导出了 prerender = true,否则 Astro 会忽略动态页面中的 getStaticPaths()。

// src/pages/[locale]/index.astro
import { locales } from "../paraglide/runtime.js";

export function getStaticPaths() {
  return locales.map((locale) => ({
    params: { locale },
  }));
}

隐藏的锚点标签

有些框架会爬取站点来发现页面。对于这类框架,可以添加隐藏的锚点标签,分别链接到当前页面的各个语言区域变体:

import { localizeHref, locales } from "@/paraglide/runtime.js";

function CrawlerLinks({ currentPath }: { currentPath: string }) {
  return (
    <nav aria-hidden="true" style={{ display: "none" }}>
      {locales.map((locale) => (
        <a key={locale} href={localizeHref(currentPath, { locale })}>
          {locale}
        </a>
      ))}
    </nav>
  );
}

爬虫会沿着这些链接抓取,并为每个语言区域生成页面。

设置语言区域

Astro (中间件)

对于 Astro SSG,推荐使用中间件,在每个页面渲染前设置语言区域:

// src/middleware.ts
import { defineMiddleware } from "astro:middleware";
import { assertIsLocale, baseLocale, setLocale } from "./paraglide/runtime.js";

export const onRequest = defineMiddleware((context, next) => {
  setLocale(assertIsLocale(context.currentLocale ?? baseLocale));

  return next();
});

这段代码在服务端静态渲染期间运行,因此 setLocale() 不会触发浏览器导航,也就不需要仅适用于浏览器的 reload: false 应急方案。

不要在 Astro SSG 中使用 paraglideMiddleware()。服务端中间件 会在 SSR 时对请求 URL 去本地化,而静态页面需要由 Astro 直接渲染每个 本地化路径。

确保 astro.config.mjs 中已配置 i18n,且其语言区域与 project.inlang 中定义的一致;同时在 baseLocale 之前添加 globalVariable,以便 setLocale() 能在静态渲染期间存储语言区域:

import { defineConfig } from "astro/config";
import { paraglideVitePlugin } from "@inlang/paraglide-js";

export default defineConfig({
  output: "static",
  i18n: {
    defaultLocale: "en",
    locales: ["en", "de", "fr"], // 必须与 project.inlang 中的语言区域一致
  },
  vite: {
    plugins: [
      paraglideVitePlugin({
        project: "./project.inlang",
        outdir: "./src/paraglide",
        emitTsDeclarations: true,
        strategy: ["url", "globalVariable", "baseLocale"],
      }),
    ],
  },
});

Next.js SSG

在构建时,将 overwriteGetLocale 与 React 的 cache 结合使用,按页面单独设定语言区域:

// app/[locale]/layout.tsx
import { cache } from "react";
import {
  getLocale,
  getTextDirection,
  overwriteGetLocale,
  baseLocale,
  assertIsLocale,
} from "@/paraglide/runtime.js";

const ssrLocale = cache(() => ({
  locale: baseLocale,
}));

overwriteGetLocale(() => assertIsLocale(ssrLocale().locale));

export default function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: { locale: string };
}) {
  ssrLocale().locale = params.locale;
  return (
    <html lang={getLocale()} dir={getTextDirection()}>
      <body>{children}</body>
    </html>
  );
}

SvelteKit

在布局的 load 函数中设置语言区域:

// src/routes/[locale]/+layout.ts
import { setLocale, assertIsLocale } from "$paraglide/runtime.js";

export function load({ params }) {
  setLocale(assertIsLocale(params.locale));
}

URL 配置

SSG 通常要求所有语言区域都带有 URL 前缀,以便为每个语言区域生成单独的文件:

compile({
  project: "./project.inlang",
  outdir: "./src/paraglide",
  emitTsDeclarations: true,
  strategy: ["url", "globalVariable", "baseLocale"],
  urlPatterns: [
    {
      pattern: "/:path(.*)?",
      localized: [
        ["en", "/en/:path(.*)?"],
        ["de", "/de/:path(.*)?"],
      ],
    },
  ],
});

这样可以确保 localizeHref() 生成带语言前缀的路径 (如 /en/about 和 /de/about) ,并分别对应独立的静态文件。

SEO:Hreflang 标签

为优化 SEO,请添加 <link rel="alternate" hreflang> 标签,帮助搜索引擎识别你的本地化页面:

import { localizeHref, locales, baseLocale } from "@/paraglide/runtime.js";

const siteUrl = "https://example.com"; // 你的生产环境 origin

function HreflangTags({ currentPath }: { currentPath: string }) {
  const currentUrl = new URL(currentPath, siteUrl).href;

  return (
    <>
      {locales.map((locale) => (
        <link
          key={locale}
          rel="alternate"
          hrefLang={locale}
          href={localizeHref(currentUrl, { locale })}
        />
      ))}
      <link
        rel="alternate"
        hrefLang="x-default"
        href={localizeHref(currentUrl, { locale: baseLocale })}
      />
    </>
  );
}

Google 要求备用 URL 必须是完整的绝对地址,且包含协议:应写 https://example.com/de/about,而不是 /de/about。使用上文的路径前缀模式时,传给 localizeHref() 的是路径,它返回的也是路径;而静态构建时没有请求可用来获取 origin,因此示例会先基于 siteUrl 将 currentPath 解析为完整 URL,再进行本地化。如果使用基于域名的本地化,请将 siteUrl 设置为能与 urlPatterns 匹配的 origin,其他语言区域则会使用各自的域名。

增量静态再生成(ISR)

Next.js 等框架支持 ISR,可在部署后按需重新生成静态页面。Paraglide 兼容 ISR:在重新生成阶段,按 SSG 的方式处理即可。设置语言区域的做法同样适用:在 Next.js 中使用 overwriteGetLocale(),确保重新生成期间语言区域的作用域正确。

另请参阅