Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
unplugin-vue-router
Advanced tools
unplugin-vue-router is a plugin for Vue.js that provides enhanced routing capabilities. It simplifies the process of defining and managing routes in a Vue.js application, offering features like automatic route generation, route guards, and more.
Automatic Route Generation
This feature allows you to automatically generate routes based on the file structure of your project. It simplifies the process of setting up routes by eliminating the need to manually define each route.
```javascript
import { createRouter, createWebHistory } from 'vue-router';
import routes from 'virtual:generated-pages';
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
```
Route Guards
Route guards are used to protect certain routes based on conditions such as authentication status. This feature allows you to define global or per-route guards to control access to different parts of your application.
```javascript
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
next({ name: 'login' });
} else {
next();
}
});
```
Dynamic Routing
Dynamic routing allows you to define routes with dynamic segments, such as user IDs. This feature is useful for creating routes that depend on variable parameters.
```javascript
const routes = [
{ path: '/user/:id', component: UserComponent }
];
const router = createRouter({
history: createWebHistory(),
routes,
});
```
vue-router is the official router for Vue.js. It provides a comprehensive set of features for routing in Vue.js applications, including nested routes, route guards, and dynamic routing. Compared to unplugin-vue-router, vue-router requires more manual setup for route definitions but offers a high level of customization.
vite-plugin-pages is a Vite plugin that automatically generates routes based on the file structure of your project. It is similar to unplugin-vue-router in that it simplifies route management, but it is specifically designed to work with Vite, a build tool that is often used with Vue.js.
Automatic file based Routing in Vue with TS support ✨
This build-time plugin simplifies your routing setup and makes it safer and easier to use thanks to TypeScript. Requires Vue Router at least 4.1.0.
⚠️ This package is still experimental. If you found any issue, design flaw, or have ideas to improve it, please, open an issue or a Discussion.
npm i -D unplugin-vue-router
// vite.config.ts
import VueRouter from 'unplugin-vue-router/vite'
export default defineConfig({
plugins: [
VueRouter({
/* options */
}),
],
})
Example: playground/
// rollup.config.js
import VueRouter from 'unplugin-vue-router/rollup'
export default {
plugins: [
VueRouter({
/* options */
}),
],
}
// webpack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-router/webpack')({
/* options */
}),
],
}
// vue.config.js
module.exports = {
configureWebpack: {
plugins: [
require('unplugin-vue-router/webpack')({
/* options */
}),
],
},
}
// esbuild.config.js
import { build } from 'esbuild'
import VueRouter from 'unplugin-vue-router/esbuild'
build({
plugins: [VueRouter()],
})
Then, you can run your dev server (usually npm run dev
to generate the first version of the types) you can replace your imports from vue-router
to vue-router/auto
:
-import { createRouter, createWebHistory } from 'vue-router'
+import { createRouter, createWebHistory } from 'vue-router/auto'
createRouter({
history: createWebHistory(),
// You don't need to pass the routes anymore,
// the plugin writes it for you 🤖
})
Alternatively, you can also import the routes
array and create the router manually or pass it to some plugin. Here is an example with Vitesse starter:
import { ViteSSG } from 'vite-ssg'
import { setupLayouts } from 'virtual:generated-layouts'
import App from './App.vue'
import type { UserModule } from './types'
-import generatedRoutes from '~pages'
+import { routes } from 'vue-router/auto/routes'
import '@unocss/reset/tailwind.css'
import './styles/main.css'
import 'uno.css'
-const routes = setupLayouts(generatedRoutes)
// https://github.com/antfu/vite-ssg
export const createApp = ViteSSG(
App,
{
- routes,
+ routes: setupLayouts(routes),
base: import.meta.env.BASE_URL
},
(ctx) => {
// install all modules under `modules/`
Object.values(import.meta.glob<{ install: UserModule }>('./modules/*.ts', { eager: true }))
.forEach(i => i.install?.(ctx))
},
)
If you are using unplugin-auto-import, make sure to remove the vue-router
preset and use the one exported by unplugin-vue-router
:
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
+import { VueRouterExports } from 'unplugin-vue-router'
export default defineConfig({
plugins: [
// other plugins
AutoImport({
imports: [
- 'vue-router',
+ { 'vue-router/auto': VueRouterExports },
],
}),
],
})
Make sure to also check and follow the TypeScript section below if you are using TypeScript or have a jsconfig.json
file.
Have a glimpse of all the existing configuration options with their corresponding default values:
VueRouter({
// Folder(s) to scan for vue components and generate routes. Can be a string, or
// an object, or an array of those.
routesFolder: 'src/pages',
// allowed extensions to be considered as routes
extensions: ['.vue'],
// list of glob files to exclude from the routes generation
// e.g. ['**/__*'] will exclude all files starting with `__`
// e.g. ['**/__*/**/*'] will exclude all files within folders starting with `__`
exclude: [],
// Path for the generated types. Defaults to `./typed-router.d.ts` if typescript
// is installed. Can be disabled by passing `false`.
dts: './typed-router.d.ts',
// Override the name generation of routes. unplugin-vue-router exports two versions:
// `getFileBasedRouteName()` (the default) and `getPascalCaseRouteName()`. Import any
// of them within your `vite.config.ts` file.
getRouteName: (routeNode) => myOwnGenerateRouteName(routeNode),
// Customizes the default langage for `<route>` blocks
// json5 is just a more permissive version of json
routeBlockLang: 'json5',
})
By default, this plugins checks the folder at src/pages
for any .vue
files and generates the corresponding routing structure basing itself in the file name. This way, you no longer need to maintain a routes
array when adding routes to your application, instead just add the new .vue
component to the routes folder and let this plugin do the rest!
Let's take a look at a simple example:
src/pages/
├── index.vue
├── about.vue
└── users/
├── index.vue
└── [id].vue
This will generate the following routes:
/
: -> renders the index.vue
component/about
: -> renders the about.vue
component/users
: -> renders the users/index.vue
component/users/:id
: -> renders the users/[id].vue
component. id
becomes a route param.Any index.vue
file will generate an empty path (similar to index.html
files):
src/pages/index.vue
: generates a /
routesrc/pages/users/index.vue
: generates a /users
routeNested routes are automatically defined by defining a .vue
file alongside a folder with the same name. If you create both a src/pages/users/index.vue
and a src/pages/users.vue
components, the src/pages/users/index.vue
will be rendered within the src/pages/users.vue
's <RouterView>
.
In other words, given this folder structure:
src/pages/
├── users/
│ └── index.vue
└── users.vue
You will get this routes
array:
const routes = [
{
path: '/users',
component: () => import('src/pages/users.vue'),
children: [
{ path: '', component: () => import('src/pages/users/index.vue') },
],
},
]
While omitting the src/pages/users.vue
component will generate the following routes:
const routes = [
{
path: '/users',
// notice how there is no component here
children: [
{ path: '', component: () => import('src/pages/users/index.vue') },
],
},
]
Note users/
could be any valid route like my-[id]-param/
.
Sometimes you might want to add nesting to the URL in the form of slashes but you don't want it to impact your UI hierarchy. Consider the following folder structure:
src/pages/
├── users/
│ ├── index.vue
│ ├── [id].vue
│ └── index.vue
└── users.vue
All generated routes that have a component
property will have a name
property. This avoid accidentally directing your users to a parent route. By default, names are generated using the file path, but you can override this behavior by passing a custom getRouteName()
function. You will get TypeScript validation almost everywhere, so changing this should be easy.
You can add route params by wrapping the param name with brackets, e.g. src/pages/users/[id].vue
will create a route with the following path: /users/:id
.
You can create optional params by wrapping the param name with an extra pair of brackets, e.g. src/pages/users/[[id]].vue
will create a route with the following path: /users/:id?
.
You can create repeatable params by adding a plus character (+
) after the closing bracket, e.g. src/pages/articles/[slugs]+.vue
will create a route with the following path: /articles/:slugs+
.
And you can combine both to create optional repeatable params, e.g. src/pages/articles/[[slugs]]+.vue
will create a route with the following path: /articles/:slugs*
.
To create a catch all route prepend 3 dots (...
) to the param name, e.g. src/pages/[...path].vue
will create a route with the following path: /:path(.*)
. This will match any route. Note this can be done inside a folder too, e.g. src/pages/articles/[...path].vue
will create a route with the following path: /articles/:path(.*)
.
It's possible to provide multiple routes folders by passing an array to routesFolder
:
VueRouter({
routesFolder: ['src/pages', 'src/admin/routes'],
})
You can also provide a path prefix for each of these folders, it will be used as is, and can therefor not end in a /
and even contain any params you want:
VueRouter({
routesFolder: [
'src/pages',
{
src: 'src/admin/routes',
// note there is always a trailing slash and never a leading one
path: 'admin/',
},
{
src: 'src/docs',
path: 'docs/:lang/',
},
{
src: 'src/promos',
// produces paths like /promos-some-file-name
path: 'promos-',
},
],
})
Note that the provided folders must be separate and one route folder cannot contain another specified route folder.
This plugin generates a d.ts
file with all the typing overrides when the dev or build server is ran. Make sure to include it in your tsconfig.json
's (or jsconfig.json
's) include
or files
property:
{
// ...
"include": [/* ... */ "typed-router.d.ts"]
// ...
}
Then, you will be able to import from vue-router/auto
(instead of vue-router
) to get access to the typed APIs. You can commit the typed-router.d.ts
file to your repository to make your life easier.
You can always take a look at the generated typed-router.d.ts
file to inspect what are the generated types. unplugin-vue-router
improves upon many of the existing types in vue-router
and adds a few ones as well:
RouteNamedMap
The RouteNamedMap
interface gives you access to all the metadata associated with a route. It can also be extended to enable types for dynamic routes that are added during runtime.
import type { RouteNamedMap } from 'vue-router/auto/routes'
Extending types with dynamically added routes:
declare module 'vue-router/auto/routes' {
import type {
RouteRecordInfo,
ParamValue,
// these are other param helper types
ParamValueOneOrMore,
ParamValueZeroOrMore,
ParamValueZeroOrOne,
} from 'unplugin-vue-router'
export interface RouteNamedMap {
// the key is the name and should match the first generic of RouteRecordInfo
'custom-dynamic-name': RouteRecordInfo<
'custom-dynamic-name',
'/added-during-runtime/[...path]',
// these are the raw param types (accept numbers, strings, booleans, etc)
{ path: ParamValue<true> },
// these are the normalized params as found in useRoute().params
{ path: ParamValue<false> }
>
}
}
RouterTyped
The RouterTyped
type gives you access to the typed version of the router instance. It's also the ReturnType of the useRouter()
function.
import type { RouterTyped } from 'vue-router/auto'
RouterLocationResolved
The RouterLocationResolved
type exposed by vue-router/auto
allows passing a generic (which autocomplete) to type a route whenever checking the name doesn't makes sense because you know the type. This is useful for cases like <RouterLink v-slot="{ route }">
:
<RouterLink v-slot="{ route }">
User {{ (route as RouterLocationResolved<'/users/[id]'>).params.id }}
</RouterLink>
This type corresponds to the return type of router.resolve()
.
You have the same equivalents for RouterLocation
, RouterLocationNormalized
, and RouterLocationNormalizedLoaded
. All of them exist in vue-router
but the one exposed by vue-router/auto
accept a generic:
// these are all valid
let userWithId: RouterLocationNormalizedLoaded<'/users/[id]'> = useRoute()
userWithId = useRoute<'/users/[id]'>()
userWithId = useRoute('/users/[id]') // 👈 this one is the easiest to write
It is possible to define named views by appending an @
+ a name to their filename, e.g. a file named src/pages/index@aux.vue
will generate a route of:
{
path: '/',
component: {
aux: () => import('src/pages/index@aux.vue')
}
}
Note that by default a non named route is named default
and that you don't need to name your file index@default.vue
even if there are other named views (e.g. having index@aux.vue
and index.vue
is the same as having index@aux.vue
and index@default.vue
).
<route>
custom blockThe <route>
custom block is a way to extend existing routes. It can be used to add new meta
fields, override the path
, the name
, or anything else in a route. It has to be added to a .vue
component inside of the routes folder. It is similar to the same feature in vite-plugin-pages to facilitate migration.
<route lang="json">
{
"name": "name-override",
"meta": {
"requiresAuth": false
}
}
</route>
Note you can specify the language to use with <route lang="yaml">
. By default, the language is JSON5 (more flexible version of JSON) but yaml and JSON are also supported. This will also add Syntax Highlighting.
extendRoutes()
You can extend existing routes by passing an extendRoutes
function to createRouter()
. This should be used as a last resort (or until a feature is natively available here):
import { createWebHistory, createRouter } from 'vue-router/auto'
const router = createRouter({
extendRoutes: (routes) => {
const adminRoute = routes.find((r) => r.name === '/admin')
if (!adminRoute) {
adminRoute.meta ??= {}
adminRoute.meta.requiresAuth = true
}
// completely optional since we are modifying the routes in place
return routes
},
history: createWebHistory(),
})
As this plugin evolves, this function should be used less and less and only become necessary in unique edge cases.
One example of this is using vite-plugin-vue-layouts which can only be used alongside extendRoutes()
:
import { createRouter } from 'vue-router/auto'
import { setupLayouts } from 'virtual:generated-layouts'
const router = createRouter({
// ...
extendRoutes: (routes) => setupLayouts(routes),
})
This project idea came from trying to type the router directly using Typescript, finding out it's not fast enough to be pleasant to use and, ending up using build-based tools, taking some inspiration from other projects like:
FAQs
File based typed routing for Vue Router
The npm package unplugin-vue-router receives a total of 440,787 weekly downloads. As such, unplugin-vue-router popularity was classified as popular.
We found that unplugin-vue-router demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.