Vite自动化注册全局组件

1 篇文章 0 订阅
1 篇文章 0 订阅

历史:

  1. 引入全局组件时单个手动引入并一个个use注册,这个组件多的时候注册代码又长又难看

  1. 写新项目的时候,公用组件通过手动引入放到一个数组中,再用遍历数组用app.component(name, component)进行注册

问题:

数组遍历的方式对于UI组件的引入,比如element-plus的按需引入,对比一个个的注册简洁了不少。但在注册自定义组件的时候,组件一多代码依旧繁琐冗余。

思路来源:

对于mixins的诸多脚本文件,我们可以通过webpackrequire.context从文件中获得到文件模块集合到一个数组中

const mixinFiles = require.context("./active-mixins", true, /\.js$/);
let mixins = [];
​
mixinFiles.keys().forEach(key => {
  let mixin = mixinFiles(key).default;
  mixins.push(mixin);
});
export default mixins;

新项目用的是vite,作为新兴的打包工具,自然也是具有这种功能

解决

从文件夹引入所有模块,遍历,导出

import { Component } from 'vue'

interface FileType {
  [key: string]: Component
}
interface componentItem {
  name: string
  sfc: Component
}

/*
 * 从common、layouts、graph文件夹导入所有的组件
 * 每一个文件需要是独立文件夹,通过index.vue导出组件
 * “组件名必须写!!!”,将自动组件名注册
 */

const commonFiles: Record<string, FileType> = import.meta.globEager(
  '/src/components/common/*/index.vue'
)
const layoutFiles: Record<string, FileType> = import.meta.globEager(
  '/src/components/layouts/*/index.vue'
)
const graphFiles: Record<string, FileType> = import.meta.globEager(
  '/src/components/graph/*/index.vue'
)

const componentList: componentItem[] = []
const files: Record<string, FileType> = Object.assign(commonFiles, layoutFiles, graphFiles)

Object.keys(files).forEach((c: string) => {
  const component = files[c]?.default
  componentList.push({ name: component.name as string, sfc: component })
})

export default componentList
import { App } from 'vue'
​
import commonComponents from './common-auto-import-components'
​
import echartsComponents from './echarts-components'
​
import elementComponents from './element-plus-components'
​
const customComponents = [
  // 便于自动注册每一个自定义组件
  ...echartsComponents,
  ...commonComponents
]
​
export default function installComponents(app: App) {
  // 按需注册elementPlus的组件
  elementComponents.forEach((component) => {
    app.use(component)
  })
  // 注册自定义组件
  customComponents.forEach((component) => {
    app.component(component.name, component.sfc)
  })
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值