-
Notifications
You must be signed in to change notification settings - Fork 382
chore: add @modern-js/plugin-i18n for locale router #7760
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
876dfa3 to
e44944b
Compare
Summary
背景
目前,在 Modern.js 中实现基于路径的国际化 (Pathname-based Internationalization) 路由需要开发者手动处理许多重复性工作,例如:
为了解决这些痛点,我们引入了一个新的官方插件
@modern-js/plugin-i18n,旨在提供一套开箱即用、遵循最佳实践的 i18n 路由解决方案。方案描述
本 PR 引入了
@modern-js/plugin-i18n,其核心设计理念是“明确优于隐式”。插件要求开发者在文件系统中显式创建 [lang] 动态路由,并在此基础上提供一系列自动化工具来简化开发。主要特性包括:
实现:通过 Server 插件注册一个全局中间件。
行为:当请求的路径不带语言前缀时(如 /about),中间件会返回一个 Redirect 响应,将其重定向到配置的回退语言路径(如 /en/about)。这确保了良好的 SEO 和用户体验。
实现:利用 Runtime 插件的 onBeforeRender 钩子。
行为:在每次页面渲染前(SSR/CSR),插件会从 URL 的 params.lang 中读取当前语言,并用它来初始化 i18next 实例。这确保了在 SSR 场景下每个请求的语言状态都是隔离且正确的。
便捷的运行时 API
我们提供了两个核心的运行时工具,从
@modern-js/plugin-i18n/runtime导出:a.
useModernI18nb.
I18nLink组件:封装了 Modern.js 的原生 Link 组件。
开发者只需提供不带语言前缀的路径,如 ,组件会自动将其转换为带当前语言前缀的完整路径,如 /en/about。
使用示例
项目安装
i18next和react-i18next依赖配置
modern.config.tssrc/modern.runtime.tsroutes/[lang]下面src ├── modern.runtime.ts └── routes ├── [lang] // 用户显式创建的动态路由目录 │ ├── about │ │ ├── page.data.ts │ │ └── page.tsx │ ├── layout.tsx // 这个布局可以获取到 lang 参数 │ └── page.tsx // 对应 /:lang └── layout.tsx // 全局根布局其他使用姿势可以参考 PR 中测试用例
Related Links
Checklist
pnpm run change.