Vue 自动注册全局组件

105 阅读1分钟

实现原理

借助webpackrequire.context函数读取特定目录下的文件,使用文件名称作为组件名称,自动注册为全局组件

关于require.context函数

webpack官方文档解释如下:

It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against.

简单的说就是此函数接收三个参数:

  • 要读取的文件夹目录
  • 是否搜索子目录
  • 一个匹配文件的正则表达式

此函数会返回一个函数

微信截图_20210903150344.png

函数本身有三个属性/方法:

  • id(属性)
  • keys(方法)
  • resolve(方法)

如图:

微信截图_20210903144236.png

使用方法

// autoSignComponents.js
// 递归读取 @/components 文件夹以及子文件夹下的vue文件
const reqCtx = require.context('@/components', true, /\.vue$/); 

// 提供install方法,供Vue.use方法调用
const install = Vue => {
    reqCtx.keys().forEach(fileName => {
        const conf = reqCtx(fileName);
        const compName = fileName.replace(/^\.\//, '').replace(/.[^/.]+$/, '');
        Vue.component(compName, conf.default || conf);
    })
}

export default { install }


//main.js
import autoSignComponents from './autoSignComponents.js';

Vue.use(autoSignComponents)