目录
一、自动引入组件
1、语法
2、使用
2.1、在compoents文件下随便创建index.js文件
2.2、mian.js引入该js
二、自动生成路由
1、示例:
2、使用
2.1、在router文件下随便创建autoRouter.js文件
2.2、在router文件下index.js文件中引入autoRouter.js文件
三、总结
一、自动引入组件
我们项目开发中,经常需要import或者export各种模块,那么有没有什么办法可以简化这种引入或者导出操作呢?答案是肯定的,下面就为大家介绍一下require.context
require.context
是 webpack
提供的一个 API,用于创建 context,即一组具有相同上下文的模块。
使用 require.context
可以方便地加载多个模块,并且可以灵活地控制模块的加载顺序和依赖关系。
以前我们都是通过import 方式引入组件
import A from 'components/A'
import B from 'components/B'
import C from 'components/C'
import D from 'components/D'
这样很蛋疼,因为每加一个组件,可能都要写这么一句,这样有规律的事,是否可以通过自动化完成?
require.context (需要vue-cli3+的版本)
1、语法
require.context(directory, useSubdirectories, regExp)
- directory: 要查找的文件路径
- useSubdirectories: 是否查找子目录
- regExp: 要匹配文件的正则
2、使用
2.1、在compoents文件下随便创建index.js文件
const requireComponent = require.context('./', true, /\.vue$/)
const install = (Vue) => {if (install.installed) returninstall.installedrequireComponent.keys().forEach(element => {const config = requireComponent(element)if (config && config.default.name) {const componentName = config.default.nameVue.component(componentName, config.default || config)}});
}if (typeof window !== 'undefined' && window.Vue) {install(window.Vue)
}export default {install
}
2.2、mian.js引入该js
import install from './compoents'
Vue.use(install)
3.3、这样在其他页面使用组件的时候,就不用再引用和注册了。直接使用就可以了。
比如直接这样使用就可以了,不用在import引入,不用components注册了。
<template><HelloWorld></HelloWorld>
</template>
二、自动生成路由
实际开发中增加一个新的页面可能就要重新编写路由的问题,导致路由文件每次都要重新编辑,页面较多,修改起来较为复杂。
那么有没有什么办法可以简化这种引入或者导出操作呢?答案是肯定的,下面就为大家介绍一下require.context
以前我们都是通过import 方式引入路由
import HomeView from '../views/HomeView.vue'Vue.use(VueRouter)const routes = [{path: '/',name: 'home',component: HomeView},{path: '/about',name: 'about',component: () => import('../views/AboutView.vue')}
]
1、示例:
require.context('./test', false, /\.test\.js$/);
//(创建出)一个 context,其中文件来自 test 目录,request 以 `.test.js` 结尾。
2、使用
2.1、在router文件下随便创建autoRouter.js文件
let routerArr = []//查找views目录,以.vue结尾的文件,查找子目录
const contexts = require.context('../views/', true, /\.vue$/)contexts.keys().forEach(value => {const path = value.substr(value.indexOf('/'), value.lastIndexOf('.') - 1)const componentLocation = value.substr(value.indexOf('.') + 1, value.lastIndexOf('.') - 1)const componentName = componentLocation.substr(componentLocation.lastIndexOf('/') + 1)//添加到路由数组中routerArr.push({path: path,name: componentName,component: () => import(`@/views${componentLocation}`)})
})export default routerArr
2.2、在router文件下index.js文件中引入autoRouter.js文件
import Vue from 'vue'
import VueRouter from 'vue-router'//引入刚刚写的autoRouter.js文件
import routerArr from './autoRouter.js'Vue.use(VueRouter)
const routes = [//这里是其他手动写的路由
]const router = new VueRouter({mode: 'history',//这里进行路由合并routes:[...routes,...routerArr]
})export default router
完成了,后面在views里面新建页面,就不要手动写路由了。
三、总结
我们可以通过require.context可以自动化引入文件。
其实我们不单单局限于组件,路由内, 所有模块文件都是通用的, 例如路由, 接口封装模块,都是可以使用的。