I'm trying to set up file system based routing for a Vue 3 application using Vite with the help of vite-plugin-pages
.
I created the project using yarn create vite
with vue-ts
as the options and added the plugin via yarn add vite-plugin-pages --dev
, yarn add vue-router
.
Following the readme on the github, I have added the following to my vite.config.ts
:
import Pages from 'vite-plugin-pages'
export default {
plugins: [
// ...
Pages(),
],
}
However, at the next step, in main.ts
:
import { createRouter } from 'vue-router'
import routes from '~pages'
const router = createRouter({
// ...
routes,
})
I cannot seem to import from ~pages
. I cannot find the module. vue-router
itself is working fine, as I can create a router fine, declaring the routes
myself. In a vite template, they seem to be using import routes from 'virtual:generated-pages'
instead and I have no idea how either works.
So, the question is, how would I go about generating the dynamic routes and as a whole, set up the usage of vite-plugin-pages
?
CodePudding user response:
You can try like this:
import Pages from "vite-plugin-pages"
export default defineConfig({
plugins: [
Pages({
pagesDir: [
{dir: 'src/pages', baseRoute: ''},
],
extensions: ['vue'],
syncIndex: true,
replaceSquareBrackets: true,
extendRoute(route) {
if (route.name === 'about')
route.props = route => ({query: route.query.q})
if (route.name === 'components') {
return {
...route,
beforeEnter: (route) => {
// eslint-disable-next-line no-console
// console.log(route)
},
}
}
},
}),
],
});
Then in main.js
import { createRouter, createWebHistory } from 'vue-router';
import generatedRoutes from 'virtual:generated-pages';
const router = createRouter({
history: createWebHistory(),
routes: generatedRoutes,
});