当前位置: 首页 > Web前端 > vue.js

vue-batchimportfiles(一)

时间:2023-03-31 23:15:52 vue.js

前言我们在创建路由的时候,会发现如果所有的路由都在一个文件中,那么当项目中的路由很多的时候,会很难找到路由,路由和routes不在一起(维护不好)等情况。因此,为了避免这种情况,我们可以使用模块化的思想来解决问题。那么,问题来了。当模块很多时,一个一个导入很浪费时间,需要重复import-assignment的过程。那么,我们能否让程序帮我们完成这一步呢?那我们玩得开心不就好了。1、webpackrequire.context按照官网解释。该方法可以在构建时解析代码中要查找的目录。通俗的说就是根据你给的规则,然后找到符合条件的文件,然后自动生成那些我们之前构建的时候需要手动导入的代码。/***可以看出该方法接受4个参数*@param{string}directory要查找的目录*@param{boolean}useSubdirectories是否查找子目录,默认true*@param{regExp}regExp文件匹配规则default/^\.\/.*$/*@param{string}模式,默认同步*@return{function}function(resolve,keys,id)*/require.context(directory,(useSubdirectories=true),(regExp=/^\.\/.*$/),(mode='sync'))/***该方法返回一个函数,有3个属性:resolve,keys,id*resolve{function},返回解析请求模块ID*keys{function},返回正则匹配文件名数组*id{string},上下文模块的模块ID*///例子,在当前目录下搜索模块,不需要搜索modules子目录,匹配规则为Alljsfilesrequire.context('./modules',false,/\.js$/);/***完整例子,自动导入路由模块*目录*-->模块*----home.js*----系统.js*/(r=>r.keys().map(key=>r(key).default))(require.context('./modules',false,/\.js$/))//console[{path:'/home'name:'home',component:()=>import('@/views/home'),},{path:'/system'name:'system',component:()=>import('@/views/system'),}]二、viteimport.meta.glob根据官网解释,该方法为懒加载方式,通过动态导入实现,我mport.meta.globEager的区别只是一种同步,一种异步,使用constmodules=import.meta.globEager('./modules/*.ts');letroutes=[];for(constkeyinmodules){modules[key]().then((mod)=>{routes.push(mod.default);})}//console[{path:'/home'name:'home',component:()=>import('@/views/home/index.vue'),},{路径:'/system'name:'system',component:()=>import('@/views/system/index.vue'),}]import.meta.globEager按照官网的说法,该方法是同步方法,可以直接导入匹配的模块constmodules=import.meta.globEager('./modules/*.ts');letroutes=[];for(constitemofObject.values(modules)){routes.push(item.default);}//console[{path:'/home'name:'home',component:()=>import('@/views/home/index.vue'),},{路径:'/system'名称:'system',组件:()=>import('@/views/system/index.vue'),}]参考webpackvite