目的:vue中引入次数频繁的公共组件,在每一个新的组件都需要通过import引入,components 注册,通过webpack自身的api实现全局引入。
// main.js
import global from "./global.js";
Vue.use(global);
// global.js
export default {
install(Vue) {
const requireComponent = require.context("@c/common", false, /\.vue$/);
requireComponent.keys().forEach(path=> {
const config = requireComponent(path);
const componentName = path.replace(/^\.\//, "").replace(/\.\w+$/, "");
Vue.component(componentName, config.default || config);
});
}
}
需要注意:全局注册的componentName 是使用组件的名称。截取组件名时需要注意路径./a.vue。
require.context(directory,useSubdirectories,regExp)
- directory:表示检索的目录
- useSubdirectories:表示是否检索子文件夹
- regExp:匹配文件的正则表达式,一般是文件名
例如:require.context("@/views/components",false,/\.vue$/)
遍历@/views/components目录文件夹下的所有以.vue结尾的vue文件,不遍历子目录;
语句执行后得到指定文件夹下的指定类型文件的执行环境。require.context()函数执行完毕返回一个函数,且函数有3个属性;
resolve {Function} -接受一个参数request,request为test文件夹下面匹配文件的相对路径,返回这个匹配文件相对于整个工程的相对路径。
resolve is a function and returns the module id of the parsed request.
keys {Function} -返回匹配成功模块的名字组成的数组。
keys is a function that returns an array of all possible requests that the context module can handle.
id {String} -执行环境的id,返回的是一个字符串,主要用在module.hot.accept。
id is the module id of the context module. This may be useful for module.hot.accept.
1525

被折叠的 条评论
为什么被折叠?



