Remix JSON 路由
remix-json-routes
是一個套件,允許您從自訂的 JSON 結構定義 Remix 路由,而不是(或除了)內建的基於檔案的路由慣例。
安裝
npm install remix-json-routes
使用 JSON 路由
您可以使用 remix.config.js
中的 routes
函數來利用此套件。 jsonRoutes
的第二個參數是一個路由陣列,類似於您在 React Router 中傳遞給 createBrowserRouter
的陣列,您可以在其中定義路由路徑資訊(path
、index
、children
),但不是指定 element
/action
/loader
/等等,而是指定指向 Remix 路由檔案的 file
路徑,該檔案會匯出這些方面。
const { jsonRoutes } = require("remix-json-routes");
/** @type {import('@remix-run/dev').AppConfig} */
module.exports = {
// Note this ignores everything in routes/ giving you complete control over
// your routes. If you want to define routes in addition to what's in routes/,
// change this to "ignoredRouteFiles": ["**/.*"].
ignoredRouteFiles: ["**/*"],
routes(defineRoutes) {
return jsonRoutes(defineRoutes, [
{
path: "/",
file: "routes/layout.tsx",
children: [
{
index: true,
file: "routes/some/path/to/home.tsx",
},
{
path: "about",
file: "routes/some/path/to/about.tsx",
},
],
},
]);
},
};
使用 JSX 路由
remix.config.js
不支援開箱即用的 JSX,但透過一個小的預構建步驟,您也可以使用 JSX 定義路由。最簡單的方法是將您的 JSX 路由定義放在一個 route.jsx
檔案中,該檔案會作為預構建步驟編譯成一個 routes.js
檔案,然後您可以從 remix.config.js
中 require
這個檔案。
建立您的 routes.jsx 檔案
此檔案應使用 remix-json-routes
中的 Route
元件匯出您的 JSX 樹狀結構
const React = require("react");
const { Route } = require("remix-json-routes");
module.exports = (
<Route path="/" file="routes/layout.tsx">
<Route index file="routes/some/path/to/home.tsx" />
<Route path="about" file="routes/testsome/path/to/about.tsx" />
</Route>
);
建立一個預構建步驟來構建 routes.js
將一個 jsxroutes
指令碼新增到 package.json
中,該指令碼會將 routes.jsx
編譯為 routes.js
,然後新增 prebuild
/predev
指令碼,以便我們在 npm run build
/npm run dev
之前始終構建 routes.js
的全新版本
{
"scripts": {
"jsxroutes": "esbuild routes.jsx --format=cjs --outfile=routes.js",
"prebuild": "npm run jsxroutes",
"predev": "npm run jsxroutes",
"build": "remix build",
"dev": "remix dev",
"...": "..."
}
}
注意 您可能也會想將
routes.js
新增到您的.gitignore
檔案中。
編輯您的 remix.config.js 以使用 jsxRoutes
// remix.config.js
const { jsxRoutes } = require("remix-json-routes");
const routes = require("./routes");
/** @type {import('@remix-run/dev').AppConfig} */
module.exports = {
ignoredRouteFiles: ["**/*"],
routes(defineRoute) {
return jsxRoutes(defineRoute, routes);
},
};