Created
April 18, 2022 17:05
-
-
Save davestewart/fe5b79a4f5ce345bff19553b88b4ef27 to your computer and use it in GitHub Desktop.
Automatically build Vue routes from all *.vue files in src/views/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from 'vue' | |
import VueRouter from 'vue-router' | |
// route helper | |
function route (path, component) { | |
if (typeof component === 'string') { | |
component = require(`../views/${component.replace('.vue', '')}.vue`).default | |
} | |
return { path, component } | |
} | |
// explicitly set home and 404 | |
const routes = [ | |
route('/', 'Home'), | |
route('*', '404') | |
] | |
// use webpack to grab all files | |
// @see https://webpack.js.org/guides/dependency-management/#context-module-api | |
const context = require.context('../views', true, /\.vue$/) | |
// add all other views as routes | |
context.keys().forEach((file, files) => { | |
// parse variables | |
file = file.substr(2) | |
const path = file | |
.replace(/\\/g, '/') | |
.replace(/(\w)([A-Z])/g, (m, a, b) => `${a}-${b}`) | |
.toLowerCase() | |
.replace('.vue', '') | |
.replace(/\/index$/, '') | |
// add routes if not yet added | |
const existing = routes.find(route => route.component.__file.replace('src/views/', '') === file) | |
if (!existing) { | |
routes.push(route('/' + path, file)) | |
} | |
}) | |
// ensure 404 is last | |
const index = routes.findIndex(route => route.path === '*') | |
routes.push(routes.splice(index, 1)[0]) | |
// debug | |
console.log(routes) | |
// setup and export final router | |
Vue.use(VueRouter) | |
const router = new VueRouter({ | |
mode: 'history', | |
base: process.env.BASE_URL, | |
routes | |
}) | |
export default router |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment