Vue 3.2 全局组件导入:解决Webpack路径问题
在使用Webpack配置Vue 3.2全局组件自动导入时,可能会遇到浏览器报错,提示组件路径错误。本文提供解决方案。
建议在./lib/index.js
文件中使用以下代码进行异步组件导入:
import { defineAsyncComponent } from 'vue';
export default {
install(app) {
const requireComponent = require.context('@/lib/', true, /.vue$/);
requireComponent.keys().forEach((fileName) => {
const componentName = fileName.split('/').pop().replace('.vue', '');
const componentPath = requireComponent(fileName).default;
const component = defineAsyncComponent(() =>
new Promise(resolve => resolve(componentPath))
);
app.component(componentName, component);
});
}
};
此方法动态导入组件,避免路径错误。 更新lib/index.js
文件后,即可正常使用全局组件。