关于vue3全局自动导入组件的问题,浏览器打开组件总是报错文件路径不对
环境为vue3.2,webpack的配置
main.js 导入了全局导入的文件
import mLibs from './lib/index'
app.use(mLibs)
./lib/index.js的内容,组件.vue都在lib文件夹下,都有文件夹包裹.此处将component常量写死了路径,效果是正常的(未注释行代码的上一行).图片放在最底部.但如果用路径拼接,就会报错'Cannot find module ',报错图片也放置在最后一行.
import { defineAsyncComponent } from 'vue'
export default {
install(app) {
// 获取当前路径任意文件夹下的 index.vue 文件
const requireComponent = require.context('@/lib/', true, /\.vue$/)
// 遍历获取到的组件模块
requireComponent.keys().forEach(fileName => {
const componentName = fileName.split('/').pop().replace('.vue', '') // 获取组件名
const componentPath = fileName.replace('.', '../lib')
const component = defineAsyncComponent(() => import('../lib/platform/roleAddEdit.vue'))
// const component = defineAsyncComponent(() => import(componentPath))
console.log(componentName, component, componentPath)
app.component(componentName, component)
})
}
}
使用场景是在element-plus中
<el-dialog
v-model='dialogShow'
:title='dialogTitle'
destroy-on-close
center
draggable
:close-on-click-modal='false'
width='450px'
>
<component @cancel='cancel' :is='componentName' :dialogTitle='dialogTitle' :form='form'></component>
</el-dialog>
const addDialogShow = () => {
dialogShow.value = true
componentName.value = 'roleAddEdit'
dialogTitle.value = '新增角色'
form.value = {}
}
还望大佬能够加以指正,非常感谢大佬
经测试将lib/index.js 改为如下代码即可