Skip to content

Instantly share code, notes, and snippets.

@jellehak
Last active February 12, 2021 09:36
Show Gist options
  • Save jellehak/9bc42d5e14e75091c5526594560c2aa1 to your computer and use it in GitHub Desktop.
Save jellehak/9bc42d5e14e75091c5526594560c2aa1 to your computer and use it in GitHub Desktop.
Automatic routes for Vue

Automatic routes for Vue

One thing I quite like from the Nuxt framework is the automatic routing capabilities. After a quick look on the web I came across https://github.com/ktsn/vue-auto-routing and a great tutorial from Michal https://codeburst.io/automatic-routing-in-vue-js-applications-1403ba425bfa. I tried to implement this plugin but it felt it could be done even more simple with the use of require.context. 

How it works

It turns this folder structure:

pages
|- dashboard
|- photos
|- users
|  |- index.vue
|  |- _id.vue

To:

[
  {
    path: "/dashboard",
    props: true,
    meta: { fileName: "./dashboard.vue", path: "./dashboard" },
    component: () => import("./dashboard.vue"),
  },
  {
    path: "/photos",
    props: true,
    meta: { fileName: "./photos.vue", path: "./photos" },
    component: () => import("./photos.vue"),
  },
  {
    path: "/users",
    props: true,
    meta: { fileName: "./users/index.vue", path: "./users/_id" },
    component: () => import("./users/index.vue"),
  },
  {
    path: "/users/:id",
    props: true,
    meta: { fileName: "./users/_id.vue", path: "./users/_id" },
    component: () => import("./users/_id.vue"),
  }
]

Configuration

Change the register script to use either dynamic imports component: () => import(${fileName}), or static imports component: requireComponent(fileName).default,

// https://webpack.js.org/guides/dependency-management/#require-context
const requireComponent = require.context(
'./', // Look for files in the @/components directory
true, // include subdirectories
// Only include "_base-" prefixed .vue files
// /_base-[\w-]+\.vue$/
// /[\w-]+\.vue$/
/\.vue$/
)
// For each matching file name...
export default requireComponent.keys().map(fileName => {
const path =
fileName
.replace(/\.\w+$/, '') // Remove extension
const toVueRouterPath = str => str
.replace('_', ':')
.replace('index', '')
.replace('.', '')
// Return proper VueRouter response
return {
path: toVueRouterPath(path),
// Dynamicly or Staticly
// component: () => import(`${fileName}`),
component: requireComponent(fileName).default,
props: true,
// Meta
meta: {
fileName,
path
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment