routes-gen เป็นเครื่องมือ CLI แบบไม่เชื่อเรื่องพระเจ้าสำหรับการแยกเส้นทางและการสร้างตัวช่วยที่ปลอดภัยสำหรับการใช้เส้นทางที่ปลอดภัย คิดว่ามันเป็น Prisma แต่สำหรับเส้นทาง
ก่อนอื่นคุณต้องติดตั้งตัวสร้างเส้นทางเอง:
yarn add routes-gen
เครื่องกำเนิดไฟฟ้าทำงานร่วมกับ "ไดรเวอร์" ซึ่งเป็นตัวแยกวิเคราะห์เส้นทางสำหรับเฟรมเวิร์กที่แตกต่างกัน
| คนขับรถ | การติดตั้ง |
|---|---|
| รีมิกซ์ | yarn add @routes-gen/remix |
| เป็นของแข็ง | yarn add @routes-gen/solid-start |
คุณสามารถเรียกใช้:
yarn routes-gen -d @routes-gen/remix
มันจะแยกวิเคราะห์และส่งออกเส้นทางตามไดรเวอร์ที่คุณให้ไว้
ตัวอย่างเช่นไดรเวอร์ @routes-gen/remix จะส่งออกเส้นทางตามค่าเริ่มต้นเป็น /app/routes.d.ts
โปรดทราบว่าคุณสามารถเปลี่ยนเส้นทางเอาต์พุตผ่าน
--outputหรือ-oFLAG
ตอนนี้คุณสามารถนำเข้าผู้ช่วย route ที่สร้างขึ้นได้ทุกที่และเพลิดเพลินกับการพิมพ์:
import { route } from "routes-gen" ;
// Compiles to /products
route ( "/products" ) ;
// Compiles to /products/1337
route ( "/products/:productId" , {
productId : "1337" ,
} ) ; คุณสามารถใช้ประเภท RouteParams เพื่อเพิ่มการพิมพ์ลงในพารามิเตอร์/เซ็กเมนต์เส้นทางไดนามิกของคุณ ตัวอย่าง:
import { RouteParams } from "routes-gen" ;
const { productId } = params as RouteParams [ "/products/:productId" ] ;ตัวอย่าง รีมิกซ์ :
import { LoaderFunction , useParams } from "remix" ;
import { RouteParams } from "routes-gen" ;
export const loader : LoaderFunction = async ( { params } ) => {
const { productId } = params as RouteParams [ "/products/:productId" ] ;
} ;
export default function Product ( ) {
const { productId } = useParams < RouteParams [ "/products/:productId" ] > ( ) ;
return < div / >;
} | ตัวเลือก | นามแฝง | คำอธิบาย |
|---|---|---|
| --ช่วย | พิมพ์ข้อความช่วยเหลือและออก | |
| -เวอร์ชัน | -v | พิมพ์เวอร์ชัน CLI และออก |
| -เอาท์พุท | -o | เส้นทางสำหรับการส่งออกเส้นทาง |
| -คนขับรถ | -d | คนขับรถจัดการเส้นทางการแยกวิเคราะห์ |
| --ดู | -w | เฝ้าดูการเปลี่ยนแปลง |
| -การส่งออกโพสต์ | ดำเนินการคำสั่งหลังจากส่งออกเส้นทาง |
หากไม่มีไดรเวอร์สำหรับเฟรมเวิร์กที่คุณต้องการคุณสามารถเขียนของคุณเอง ตัวอย่างเช่นสร้างไฟล์ driver.js อย่างง่ายในโครงการของคุณด้วยเนื้อหาต่อไปนี้:
module . exports = {
// Where to export the typings if the "output" flag was not provided.
defaultOutputPath : "src/routes.d.ts" ,
// The routes parser. Must export and array of routes matching the { path: string } interface.
routes : async ( ) => {
return [
{
path : "/products" ,
} ,
{
path : "/products/:productId" , // Note that the dynamic segments must match the :myVar pattern.
} ,
] ;
} ,
// The paths to be watched for changes. Must return and array of relative paths.
watchPaths : async ( ) => {
return [ "/my-routes/**/*.{ts,tsx,js,jsx}" ] ;
} ,
}ตอนนี้คุณสามารถใช้งานได้อย่างง่ายดาย:
routes-gen -d driver.js
นอกจากนี้คุณยังสามารถเผยแพร่ไปยัง NPM ติดตั้งและใช้เป็นแพ็คเกจ:
routes-gen -d my-driver-package
โปรดพิจารณาส่งไดรเวอร์ของคุณไปยังที่เก็บนี้