1.require.context(directory,useSubdirectories,regExp)
directory
:表示检索的目录
useSubdirectories
:表示是否检索子文件夹
regExp
:匹配文件的正则表达式,一般是文件名
例如 require.context("@/views",false,/.vue$/)
2.在vue中使用
目录结构如下:
home.crouter.js内容如下:
export default {
path: '/',
component: () => import('@/views/home/index'),
meta: {
title: '首页'
},
children: []
}
index.js中的处理
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
let cRouter = []
let aRouter = []
function importAll(r, list) {
r.keys().forEach((key) => list.push(r(key).default))
}
importAll(require.context('.', false, /\.crouter\.js/), cRouter)
importAll(require.context('.', false, /\.arouter\.js/), aRouter)//.再这里表示当前目录
export const constRouter = [...cRouter];
console.log(constRouter); //
export const asyncRouter = [...aRouter]
console.log(asyncRouter); //
export const testRouter = [...asyncRouter, ...constRouter]
export default new Router({
mode: 'history',
base: '',
routes: testRouter
})