1.require.context(directory,useSubdirectories,regExp)
directory
:表示檢索的目錄
useSubdirectories
:表示是否檢索子文件夾
regExp
:匹配文件的正則表達式,一般是文件名
例如 require.context("@/views",false,/.vue$/)
2.在vue中使用
目錄結(jié)構(gòu)如下:
home.crouter.js內(nèi)容如下:
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
})