vite 动态导入路由:
router/index.js文件
- //vite 下面寻找 views 文件夹下面所有的page.js文件
- let pageList = import.meta.glob('../views/**/page.json', {
- eager: true,
- import: 'default',
- });
- //所有的文件
- const modules = import.meta.glob('../views/**/**.vue');
-
- //遍历
- let pages = Object.entries(pageList).map(([path, meta]) => {
- let pathName = path.slice(8, -10);
- let name = pathName.slice(1).split('/').join('-');
- let fileName = path.slice(0, -10);
- let fixFileName = fileName.split('/').pop();
- let filePath = fileName + '/' + fixFileName + '.vue';
-
- return {
- path: pathName,
- name: name,
- component: modules[filePath],
- meta,
- };
- });
-
- routes: [
- {
- path: '/',
- name: 'layout',
- redirect: '/home',
- component: () => import('../components/layout/layout.vue'),
- meta: {
- title: '首页',
- },
- children: pages,
- },
- {
- path: '/login',
- name: 'login',
- component: () => import('../views/login.vue'),
- meta: {
- title: '登录',
- },
- },
- ],
以下是 截图:
这个是webpack 动态导入路由:
- //读取配置文件
- const context = require.context('../components/page', true, /\.json$/);
- //读取路由文件
- const contextVue = require.context('../components/page', true, /\.vue$/);
-
- let fileObj = {};
- //动态读取文件
- contextVue.keys().map(key => {
- let keyName = key.slice(1);
- fileObj[keyName] = contextVue(key).default;
- });
-
- let routerPathArr = [];
- //动态配置路由
- context.keys().forEach(key => {
- let obj = context(key);
- let compKey = obj['componentPath'];
- let routeObj = {
- path: obj['path'],
- name: obj['name'],
- component: fileObj[compKey],
- meta: obj['meta']
- };
- routerPathArr.push(routeObj);
- });
以下是截图: