Vue3自动注册组件

1、webpack中使用require.context

require.context(directory, useSubdirectories, regExp)

directory: 文件路径

useSubdirectories: 是否查找子目录

regExp: 匹配正则

export default {
  install(app: App): void {
    const comps = require.context('./', true, /index\.vue$/)
    comps.keys().forEach((key) => {
      const compName = 'm-' + key.replace('./', '').split('/')[0]
      app.component(compName, comps(key).default)
    })
  }
}

2、vite中使用import.meta.glob

// const components = import.meta.glob('./*/index.vue')
// 转译为
// const modules = {
//     './icon/index.vue':()=>import('./icon/index.vue')
// }

export default {
    install(app:App){
        const components = import.meta.glob('./*/index.vue')
        for(const [key,val] of Object.entries(components)){
            const componentName = 'm-'+key.replace('./','').split('/')[0]
            app.component(componentName,defineAsyncComponent(val))
        }
    }
}

3、webpack中批量导入svg矢量图标

// 导入所有svg图标
const svgRequire = require.context('./svg', false, /\.svg$/)
svgRequire.keys().forEach((svgIcon) => svgRequire(svgIcon))

安装svg-sprite-loader,在vue.config.js中配置

chainWebpack: (config) => {
    config.module.rule('svg').exclude.add(resolve('src/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
  },

使用时

const iconName = computed(() => `#icon-${props.icon}`)
<svg v-else class="svg-icon" :class="className" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>

4、在vite中批量导入svg使用vite-plugin-svg-icons的createSvgIconsPlugin函数

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值