how to generate the path like router config in vite + react + react-router project

when i use react-router and vite, i want to config my router in the router.config.ts file and also generate some config for the target path dir. (like the nextjs router which is automatically generated based on the file structure)
config the router in the router.config.ts file is easy, but how to generate the path like router config for the target path dir? and combine the self config and automatically generated config together, finally use it in the react router?
we can split the problem into these parts:
  1. generate the path like router config for the target path dir
  1. combine the self config and automatically generated config together
  1. use it in the react router

1. generate the path like router config for the target path dir

there is one package called vite-plugin-pages, which can help us generate the path like router config for the target path dir.
how to use it?
step 1. in the vite + react + react-router project, install the vite-plugin-pages package.
step 2. add the vite-plugin-pages plugin in the vite config file.
the default dirs of the vite-plugin-pages plugin is src/pages, you can change it by the dir option.
we set it to src/views in the example.
notion image
it has some other options, you can see the official docs.
step 3. get the path like router config for the target path dir.
then we can view the target path which is related to the target path dir.
step 4. (optional) generate the sidebar to show the levels of the path.

2. combine the self config and automatically generated config together

since the dirs of the vite-plugin-pages plugin is src/views (we config it in the step 2), so we can combine the self config and automatically generated config together.
we need to create a dir which is not in the src/views dir(such as src/pages)

3. use it in the react router

the use way is the same as the react-router

summary

this is a simple way to generate the path like router config for the target path dir in the vite + react + react-router project.
if you want to see a demo, you can see the demo repo.
if you want to know more about the vite-plugin-pages plugin, you can see the github repo.
上一篇
how to make a hollow cylinder in blender
下一篇
原来亲人在侧,是我最深重的感谢

相关文章