利用 webpack 的 require.context 在 vue 文件中批量导入组件

通过下面的方法可以读取 components 文件夹下的 vue 文件并放到 map 对象中

const context = require.context('./components/', false, /\.vue$/)
const map = {}
for (const key of context.keys()) {
  // key 是文件的路径,下面的 match 是抽出文件名作为组件名
  const componentName = key.match(/\/?([^/]+)\.vue$/)
  map[componentName] = context(key)
}
console.log(map)

然后在 vue 文件的 components 配置中直接配置上面的 map

export default defineComponent({
  components: {
    componentOther, // 不在上面 map 中的组件
    ...map
  }
})

参考资料

posted @   尹宇星_Kim  阅读(256)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示