参考:
作用:
当我们需要对某一目录下的文件进行引用时,可以进行一次性引用,不用手动一堆import,实现前端自动化引入,让你的代码看起来高大上。
语法
- 该方法的三个参数
- 上下文,即目录路径
- 是否所搜子目录
- 匹配正则表达式
//语法
require.context(directory, useSubdirectories = false, regExp = /^\.\//);
//例子
//test文件下所有js文件
require.context('./test', false, /\.js$/);
- 导出功能context的3个属性
- resolve 函数,传入参数key返回该key模块的id
- keys 模块路径组成的数组
- id 上下文路径
实例
以crm新系统vuex为例
目录结构
-store
--modules
--call-center.js
--common.js
--follow-node.js
--等等
--index.js
代码如下
import Vue from 'vue';
import Vuex from 'vuex';
import common from './modules/common';
import camelcase from 'camelcase';
Vue.use(Vuex);
//引入modules下的所有模块
const context = require.context('./modules', false, /\.js$/);
const moduleStores = {};
//console.dir(context);
//导出的功能context有3个属性:resolve,keys,id
//resolve是个函数,传入模块返回该模块id(模块路径),
console.log('resolve', context.resolve);
//返回以引用模块组成的数组
console.log('keys', context.keys());
console.log('ids', context.id);
打印结果如下
resolve ƒ webpackContextResolve(req) {
var id = map[req];
if(!(id + 1)) { // check for number or string
var e = new Error("Cannot find module '" + req + "'");
e.code = 'MODULE_NOT_FOUND';
throw e;
}
…
keys (7) ["./call-center.js", "./common.js", "./follow-node.js", "./organization.js", "./student-detail.js", "./ui.js", "./user.js"]
ids ./src/store/modules sync \.js$
继续代码
context.keys().forEach(key => {
//截取文件名 ./call-center.js ====> call-center
const fileName = key.slice(2, -3);
//用驼峰插件修改为驼峰命名 call-center =====> callCenter
const fileNameInCamelCase = camelcase(fileName);
//context作为一个函数,也接受一个req参数,这个和resolve方法的req参数是一样的
//传入key值获取对应模块,因为是export default导出的,所以default属性包含模块内容
const fileModule = context(key).default;
if (fileName === 'common') {
return;
}
//将模块解构挂载moduleStores对应的属性上,
moduleStores[fileNameInCamelCase] = {
...fileModule,
//命名空间不是很了解,
namespaced: true,
};
});
export default new Vuex.Store({
modules: {
//挂载模块
...moduleStores,
common,
},
});