Vite 项目中批量导入 Vue 组件

332 阅读1分钟

当需要从同一目录中导入多个 Vue 组件时,逐个手动导入可能会非常繁琐;此时批量导入所有组件可以显著提高效率和便捷性。

以下是在 Vite 项目中实现 Vue 组件批量导入的方案

  1. 在需要导出组件的目录下新建imports.js
// 导入当前目录下的所有 vue 组件
const allFiles = import.meta.glob("./*.vue", { eager: true });

const components = Object.keys(allFiles).reduce((acc, path) => {
  // 获取组件配置
  const component = allFiles[path].default || allFiles[path];
  // 获取组件的 PascalCase 命名
  const componentName = path
    .split("/")
    .pop()
    .replace(/\.\w+$/, "");
  // 将组件添加到对象中
  acc[componentName] = component;
  return acc;
}, {});

export default components;

  1. 在需要导入组件的文件中引入imports.js,并注册组件
<template>
  <Icon />
  <component :is="components.Button" />
</template>

<script setup>
import components from "./modules/imports.js";

// 直接通过组件名引用的组件,需要解构出来
const { Icon } = components;
</script>