modern.js icon indicating copy to clipboard operation
modern.js copied to clipboard

[Feature]: 支持類似 Next.js rewrites 功能

Open rosslo opened this issue 8 months ago • 3 comments

这个功能解决了什么问题?

我們的項目可能根據不同站點,會有支持 "國際化(i18n ) 路由" 或不支持的場景。

開啟國際化(i18n ) 路由: https://.com//home 關閉國際化(i18n ) 路由: https://-sg.com/home

參考 Next.JS 的配置:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/:locale/home',
        destination: '/home',
      },
    ]
  },
}

能夠實現 "/en/home" 或是 "/home" 都是指向到渲染 /routes/home/page.tsx

你期望的 API 是什么样子的?

希望 https://modernjs.dev/apis/app/runtime/web-server/hook.html 能夠提供一個 beforeMatch 的鉤子,在 modernjs 開始處理頁面渲染前,能提供以下能力:

  1. 提供開發者對 request 資訊做判斷,判斷是否要 rewrite 或 redirect
  2. ctx.router.rewrite(...) 方法,能夠實現同 Next.JS 的 rewrites 功能,支持 sourcedestination 參數
import type { BeforeMatch } from '@modern-js/runtime/server';

export const beforeMatch: BeforeMatch = async (ctx, next) => {
  if (ctx.request['i18n-base-path']) {
     ctx.router.rewrite({
       source: ctx.request.url,
       destination: ctx.request.url.replace(`/${ctx.request['i18n-base-path']}`, '')
     });

     next()
  } else {
     next()
  }
};

rosslo avatar Apr 25 '25 04:04 rosslo

类似的功能已经规划了,但目前还未确定准确的支持时间,可以先使用 data loader + redirect API 处理

yimingjfe avatar Apr 25 '25 06:04 yimingjfe

請問能夠提供示範的案例嗎?

我們項目的結構如下:

└── routes
    ├── layout.tsx
    ├── layout.data.tsx
    └── home
        └── page.tsx
        └── page.data.tsx

我理解,基於上述結構 "/en/home" 會是被定向到 404 想請教我該如何使用 您上述提到的 "data loader + redirect API",實現 "/en/home" 能夠渲染 /routes/home/page.tsx 的內容?

另外,我們不考慮新增頂層 /routes/[lng$] 文件結構,是因為有 /routes/[lng$]/[service] 存在可能,會導致 "/:lng/home" 或 "/home/:tab" 可能匹配到同個 page.tsx

rosslo avatar Apr 25 '25 06:04 rosslo

正如 @yimingjfe 所说的,rewrite 相关功能我们正在开发。

如果考虑的简单一点,直接为入口添加一个 /en 的 baseUrl,不知道能否解决问题。 https://modernjs.dev/zh/configure/app/server/routes.html

zllkjc avatar Apr 27 '25 07:04 zllkjc