Transform file system directory into vue-router routes using webpack
Only works with webpack. Resulting route structure and file naming rules should be similar to Nuxt Pages.
Turns out you don't need Vite or compile-time plugins.
npm i Heniker/vue-route-builder
import * as Router from 'vue-router'
import { buildPages } from 'vue-pages-builder'
const routes = [
...otherRoutes,
...buildPages(
require.context('./pages', true, /.*\.vue/, 'weak'),
require.context('./pages', true, /.*\.vue/, 'lazy' /* or any other except weak */)
),
]
Router.createRouter({ routes })
It should work exactly the same way as Nuxt Pages directory does.
In order to get TS types for require.context
it is possible to npm i @types/webpack-env -D
You may also need to specify
{
"compilerOptions": {
"types": ["webpack-env"]
}
}
in tsconfig.json
I tested it with "vue-router": "^4.0.11"
, but version 4 did not introduce route structure changes. It should work with vue-router 3
, although there might be TS erros.
It's a webpack thing one can use to explicitly create a runtime chunk. More info here - webpack requirecontext and here - webpack dynamic expressions. I'd even suggest reading full webpack documentation, it's pretty rad.
First argument - weak context
is required to list files in way that doesn't pull them into the bundle.
The second argument is what does the actual components import and I decided to expose it for easier control. You can choose how you want your pages to be loaded (lazy-loading, include into the main bundle, or use seperate bundle and load altogether). More info in that rad webpack documentation - possible options other than 'lazy', more about context