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/etc.,而是指定 file 路径,指向导出这些方面的 Remix 路由文件。
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
向 package.json 添加一个 jsxroutes 脚本,该脚本会将 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);
},
};