一. 概念
一个webpack的api,通过执行require.context函数获取一个特定的上下文,主要用来实现自动化导入模块,在前端工程中,如果遇到从一个文件夹引入很多模块的情况,可以使用这个api,它会遍历文件夹中的指定文件,然后自动导入,使得不需要每次显式的调用import导入模块,webpack官网介绍
二. 应用场景
(1) 批量导入js文件(例如引入路由文件)
导入及使用
// 导入
const asyncFiles = require.context('./permissionModules', true, /\.ts$/)
let permissionModules: Array<RouteRecordRaw> = []
asyncFiles.keys().forEach((key) => {
if (key === './index.ts') return
permissionModules = permissionModules.concat(asyncFiles(key).default)
})
// 使用
export const constantRoutes: Array<RouteRecordRaw> = [
{
path: '/redirect',
component: Layout,
meta: { hidden: true },
children: [
{
path: '/redirect/:path(.*)',
component: () => import(/* webpackChunkName: "redirect" */ '@/views/redirect/Index.vue')
}
]
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [
{
path: 'dashboard',
component: () => import(/* webpackChunkName: "dashboard" */ '@/views/dashboard/Index.vue'),
name: 'Dashboard',
meta: {
title: 'dashboard',
icon: '#icondashboard',
affix: true
}
}
]
},
...constantModules
]
export const asyncRoutes: Array<RouteRecordRaw> = [
...permissionModules
]
目录解构
单个文件代码示例
import { RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/Index.vue'
const chartsRouter: Array<RouteRecordRaw> = [
{
path: '/charts',
component: Layout,
redirect: 'noredirect',
name: 'Charts',
meta: {
title: 'charts',
icon: '#iconchart1'
},
children: [
{
path: 'bar-chart',
component: () =>
import(
/* webpackChunkName: "BarChart" */ '@/views/charts/BarChartDemo.vue'
),
name: 'BarChartDemo',
meta: {
title: 'barChart',
noCache: true
}
},
{
path: 'line-chart',
component: () =>
import(
/* webpackChunkName: "LineChart" */ '@/views/charts/LineChartDemo.vue'
),
name: 'LineChartDemo',
meta: {
title: 'lineChart',
noCache: true
}
},
{
path: 'mixed-chart',
component: () =>
import(
/* webpackChunkName: "MixedChat" */ '@/views/charts/MixedChatDemo.vue'
),
name: 'MixedChartDemo',
meta: {
title: 'mixedChart',
noCache: true
}
}
]
}
]
export default chartsRouter
(2) 批量导入.vue文件
原理同导入js文件,不同点是用到了path及components的处理
// 1. 在组件里面使用
const path = require('path')
const files = require.context('./components/H5Campaign', false, /\.vue$/)
const modules = {}
console.log(files.keys())
files.keys().forEach(key => {
const name = path.basename(key, '.vue')
modules[name] = files(key).default || files(key)
})
// components
components: modules
// 2. 导入全局组件(vue3.0)
import { createApp } from 'vue'
const app = createApp({})
app.component(
// 注册的名字
name,
// 组件的实现
files(key).default || files(key)
)
});
三. 总结
- require.context也可以用于批量导入图片,但是显示时可能会不符合预期;
- js调试时,通常会碰到用console.log打印函数属性时不显示的问题,这时可以尝试用console.dir
- path是Node.js下的模块,path.basename() 方法返回 path 的最后一部分,类似于 Unix basename 命令。 尾随的目录分隔符被忽略,详情可查询Node.js官方文档