代码说明:
- `export default : 开始定义一个导出的对象。
install(app) : 这是一个名为install的方法,它接受一个参数app。通常在 Vue.js 插件中,install` 方法用于在 Vue 应用中添加一些功能。const ctx = require.context('./', true, /.vue$/): 使用require.context来加载当前目录下的.vue文件。'./'表示当前目录,true表示使用绝对路径,/.vue$/则是一个正则表达式,匹配所有.vue文件。ctx.keys().forEach: 获取所有.vue文件的键(也就是文件名),然后遍历它们。const component = ctx(item).default: 通过ctx(item)加载每个文件,然后获取其默认导出(通常是一个组件)。app.component(item.split('/')[1], component): 使用app.component方法将加载的组件注册为全局组件。这里使用split('/')[1]来获取文件名(不包括路径和扩展名)。
export default {
install(app) {
const ctx = require.context('./', true, /\.vue$/)
ctx.keys().forEach(item => {
const component = ctx(item).default
app.component(item.split('/')[1], component)
})
},
}
在main.ts中使用
import { createApp, AppInstance } from 'vue';
import App from './App.vue'
const app: AppInstance = createApp(App);
app.use(com)
在vite中批量注册组件
假设你有一个目录,其中包含了一些 .vue 文件,你希望动态地导入这些文件并注册为 Vue 组件。你可以创建一个 components.js 文件,然后在这个文件中使用 import 语句来导入目录中的所有 .vue 文件。
在 components.js 文件中,你可以这样做:
npm install fs path vue-template-compiler --save
import { createApp } from 'vue';
import { createVite } from 'vite-plugin-vue';
import { compile } from 'vue-template-compiler';
import * as fs from 'fs';
import path from 'path';
const vite = createVite({ root: path.resolve('src') });
const app = createApp({});
// 获取目录下的所有 .vue 文件
const vueFiles = fs.readdirSync(path.resolve('src/components')).filter(file => file.endsWith('.vue'));
// 循环遍历所有 .vue 文件并导入
for (const vueFile of vueFiles) {
const filePath = path.resolve('src/components', vueFile);
const fileContent = fs.readFileSync(filePath, 'utf-8');
const template = compile(fileContent).render;
const component = { template };
app.component(vueFile.replace('.vue', ''), component); // 注册为全局组件
}
app.$mount('#app'); // 在 #app 挂载点渲染应用