使用require.context代替大量使用import

1.require.context()

1
2
3
4
5
6
/**
* dir:要查找的文件路径
* useSubdirectories:是否查找子目录
* regExp:要匹配文件的正则
*/
require.context(dir, useSubdirectories, regExp)

2.使用


目录结构

1
2
3
4
5
6
src
├── components
| ├─ A.js
| ├─ B.js
| └─ C.js
└── index.js
1
2
3
4
5
6
7
// index.js
const ctx = require.context('./components/', true, /\.js$/)
console.log(ctx.id) // './src/components'
// 返回的是模块内部变量map的keys,通过模块提供的keys()方法访问
console.log(ctx.keys()) // ['./A.js', './B.js', './C.js' ]
// 返回相对于整个工程的相对路径
console.log(ctx.resolve('./A.js')) // './src/components/A.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
var map = {
"./A.js": "./src/components/A.js",
"./B.js": "./src/components/B.js",
"./C.js": "./src/components/C.js"
};

function webpackContext(req) {
var id = webpackContextResolve(req);
return __webpack_require__(id);
}
function 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;
}
return id;
}
webpackContext.keys = function webpackContextKeys() {
return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
webpackContext.id = "./src/components sync recursive \\.js$";
module.exports = webpackContext;

2.实际使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// ./src/components/index.js

// 查找当前目录下所有的index.vue
const ctx = require.context('./', true, /index\.vue$/)

// install() 被Vue.use()调用
export default {
install: (Vue) => {
ctx.keys().forEach(i => {
const component = ctx(i).default
Vue.component(component.name, component)
})
}
}
1
2
3
4
5
6
// ./src/main.js
import Vue from 'vue'
import Components from '@/components/index.js'

// 全局注册公用组件
Vue.use(Components)

最后更新: 2021年11月30日 15:40