使用 require.context 进行批量导入,不仅可以减少代码, 后期添加新的文件不用在挨个引入。
如果你恰好使用了 webpack (或在内部使用了 webpack 的 Vue CLI 3+),那么就可以使用 require.context 只全局注册这些非常通用的基础组件。注意:全局注册的行为必须在根 Vue 实例 (通过 new Vue) 创建之前发生。

使用 require.context 进行批量导入,不仅可以减少代码, 后期添加新的文件不用在挨个引入,引入后回调一个方法 , 该方法需传递一个文件的路径参数,得到相应的文件模块,其中有 keys 和 resovle 函数 keys 它返回一个数组,数组中所有子集都可以被 require。
context 所返回的 webpackContext 函数处理 resolve 它返回 request 被解析后得到的模块 id,其中 webpack 还有闭包 map 函数 , 该函数接受一个函数参数, 函数中默认参数包含了所有匹配的子模块的路径。

vue2 官方文档中,在应用入口文件 (比如 src/main.js) 中全局导入基础组件的示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import Vue from "vue";
import upperFirst from "lodash/upperFirst";
import camelCase from "lodash/camelCase";

const requireComponent = require.context(
// 其组件目录的相对路径
"./components",
// 是否查询其子目录
false,
// 匹配基础组件文件名的正则表达式
/Base[A-Z]\w+\.(vue|js)$/
);

requireComponent.keys().forEach((fileName) => {
// 获取组件配置
const componentConfig = requireComponent(fileName);

// 获取组件的 PascalCase 命名
const componentName = upperFirst(
camelCase(
// 获取和目录深度无关的文件名
fileName
.split("/")
.pop()
.replace(/\.\w+$/, "")
)
);

// 全局注册组件
Vue.component(
componentName,
// 如果这个组件选项是通过 `export default` 导出的,
// 那么就会优先使用 `.default`,
// 否则回退到使用模块的根。
componentConfig.default || componentConfig
);
});

vuex 自动引入 modules 文件夹下的所有 js 文件(无需一个个引入)

示例:src/store/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
import getters from "./getters";
// require.context函数接受三个参数 1.读取的文件路径 2.是否遍历文件的子目录 3.匹配文件的正则
// 表示获取同级目录modules文件夹下的 所有 js文件(这样就不用一个个引入了)

const modulesFiles = require.context("./modules", true, /\.js$/);
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
const value = modulesFiles(modulePath);
modules[moduleName] = value.default;
return modules;
}, {});

// console.log('modules', modules)

const store = new Vuex.Store({
modules, // 对象,key是文件名,value是相应内容
getters,
});

export default store;