Skip to content

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

@rosslo

Description

@rosslo

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

我們的項目可能根據不同站點,會有支持 "國際化(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()
  }
};

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions