----vue 高频组件全局注册----

使用require.context实现前端工程自动化快速应用到项目中

require.context是什么?

一个webpack的api,通过执行require.context函数获取一个特定的上下文,主要用来实现自动化导入模块,在前端工程中,如果遇到从一个文件夹引入很多模块的情况,可以使用这个api,它会遍历文件夹中的指定文件,然后自动导入,使得不需要每次显式的调用import导入模块

分析require.context

require.context函数接受三个参数

  • directory {String} -读取文件的路径
  • useSubdirectories {Boolean} -是否遍历文件的子目录
  • regExp {RegExp} -匹配文件的正则
语法: require.context(directory, useSubdirectories = false, regExp = /^.//);
//新建index.js文件
// import Vue from "vue"; function changeStr(str) { //首字母大写 return str.charAt(0).toUpperCase() + str.slice(1); } //找到上一级common目录下的.vue结尾的所有文件 const requireComponent = require.context("@/components", false, /\.vue$/); console.log(requireComponent,"hahaa"); //["./child1.vue", "./child2.vue"] const install = (Vue) => { requireComponent.keys().forEach((fileName) => { let config = requireComponent(fileName); let componentName = changeStr( fileName.replace(/^\.\//, "").replace(/\.\w+$/, "") ); console.log(config); // console.log(componentName); //Child1 Child2 Vue.component(componentName, config.default || config); }); }; export default { install, };

 最后,在main.js引入该文件Vue.use(index)

原文链接:https://juejin.im/post/5e8d43d451882573744c5b65

posted @ 2020-04-08 19:10  BenSan、  阅读(272)  评论(0编辑  收藏  举报