当我们处理vue中的路由时,常见的写法如下:
以如下项目结构为例:
-
-
import childrenRelation from "./module/childrenRelation" import login from "./module/login" import operateDoc from "./module/operateDoc" import otherService from "./module/otherService" import payment from "./module/payment" const router = createRouter({ history:createWebHashHistory(), routes:[ ...childrenRelation, ...login, ...operateDoc, ...otherService, ...payment ] }) -
当页面多起来,路由文件也多起来的时候,还是这样的引入方式,页面会很冗长,不优雅
要优雅,怎么办,import.meta.globEage这不就来了
import.meta.globEage工程化方案
-
【代码截图】
const fileArr:any = [] //获取文件内容对象,key为文件路径名称,value是对应的文件返回的模块内容,参考下面【控制台截图】 const routerFiles = import.meta.globEager('./module/*.ts') console.log('routerFiles:',routerFiles) Object.keys(routerFiles).forEach(filename=>{ //将具体的路径内容push到接受变量中,根据业务需求,这里可以做不同的处理 fileArr.push(...routerFiles[filename].default) }) const router = createRouter({ history: createWebHashHistory(), routes:fileArr }) -
【控制台截图】
webpack项目也有类似的工程化方法require.context
require.context(file,flag,reg)
- file:要遍历的文件夹路径,返回一个file函数对象,与vite返回的object对象略有不同
- flag:是否遍历下一级子目录
- reg:要匹配的文件的正则
-
【页面代码截图】:
-
【a.js截图】
-
【控制台截图2】
代码简析
//遍历modules目录下面的所有的.js文件,并返回一个file函数对象,与vite返回的object对象略有不同 let files = require.context('./modules',true,'\.js$') //获取files对象的键值数组,返回的是['./a.js','./b.js'],案例参考下面代码截图以及控制台截图 let keys = files.keys() //后面根据当前获取的数据结合业务进行具体的处理即可
总结下来就是以下两个方法的使用
- import.meta.globEager(file)(vite项目)
- require.context(file,flag,reg) (webpack项目)