熊浩宇
发布于 2023-08-14 / 0 阅读 / 0 评论 / 0 点赞

vue批量导入组件

  1. node

    import Vue from 'vue'
    
    export default {
    	install() {
    		// 批量注册公用组件
    		const components = require.context('@/components', true, /\.vue$/)
    		components.keys().map(path => {
    			// 获取组件文件名
    			const fileName = path.replace(/(.*\/)*([^.]+).*/ig, '$2')
    			if (fileName.indexOf('apps-') === 0 || fileName.indexOf('v-') === 0) {
    				// 使用文件名
    				Vue.component(`${fileName}`, components(path).default || components(path))
    			}
    		})
    	}
    }
  2. vite

    const components = import.meta.globEager('@/components/**/*.vue');  // 文件路径
    export default {
      install: (app: any) => {
        Object.keys(components).forEach((component) => {
          const index = component.lastIndexOf('/');
          // 文件名
          const name = component.substring(index + 1, component.length).replace('.vue', '');
          app.component(name, (components[component] as any).default);
        });
      },
    };

评论