简化import 或者export各种模块
require.context(directory,useSubdirectories,regExp)
1 directory 要查找的文件路径
2 useSubDirectories 是否查找子目录
3 regExp 要匹配文件的正则
require.context('',true,/.js$/);
返回:
1 var map = { 2 "./A.js": "./src/components/test/components/A.js", 3 "./B.js": "./src/components/test/components/B.js", 4 "./C.js": "./src/components/test/components/C.js", 5 "./D.js": "./src/components/test/components/D.js" 6 }; 7 8 9 function webpackContext(req) { 10 var id = webpackContextResolve(req); 11 return __webpack_require__(id); 12 } 13 function webpackContextResolve(req) { 14 var id = map[req]; 15 if(!(id + 1)) { // check for number or string 16 var e = new Error("Cannot find module '" + req + "'"); 17 e.code = 'MODULE_NOT_FOUND'; 18 throw e; 19 } 20 return id; 21 } 22 webpackContext.keys = function webpackContextKeys() { 23 return Object.keys(map); 24 }; 25 webpackContext.resolve = webpackContextResolve; 26 module.exports = webpackContext; 27 webpackContext.id = "./src/components/test/components sync recursive \.js$";
reuqire.context()返回webpackContext,有两个静态方法keys和resolove,一个id属性。
keys 返回匹配成功模块的名字组成的数组
resolve 接受一个参数request,request为test文件夹下面匹配文件的相对路径,返回这个匹配文件相对于整个工程的相对路径
1 const ctx = require.context('./components/', true, /.js$/) 2 console.log(ctx.keys()) 3 // ["./A.js", "./B.js", "./C.js", "./D.js"]
demo:
1 global.js 在main.js中引入 2 import Vue from 'vue'; 3 function changeStr(str){return str.chartAt(0).toUpperCase()+str.slice(1)} 4 const requireComponent=require.context('./',false,/.vue$/); 5 6 const install=()=>{ 7 requireComponent.keys().forEach(fileName=>{ 8 let config=requireComponent(fileName); 9 let componentName=changeStr(fileName.replace(/^.//,'').replace0(/.w+$//,'')); 10 Vue.component(componentName,config.default||config); 11 }); 12 } 13 export default{install}