如何从文件夹导入所有Vue组件?

时间:2019-01-24 10:14:57

标签: vue.js webpack vuejs2 vue-component

我正在尝试从文件夹自动加载所有vue组件, 如果我不使用 vue“ Async Components”,这会很好。

一旦我尝试将异步组件与 import 一起使用,就会收到此错误:

10:11-36 Critical dependency: the request of a dependency is an expression

我的代码加载了所有组件,这些组件会产生此错误:

const ComponentContext = require.context('./', true, /\.vue$/i);

ComponentContext.keys().forEach((componentFilePath) => {

    const componentName = componentFilePath.split('/').pop().split('.')[0];
    Vue.component(componentName, () => import(componentFilePath));

});

如何解决此问题?还是有其他方法可以做到这一点?

3 个答案:

答案 0 :(得分:0)

代替

Vue.component(componentName, () => import(componentFilePath));

尝试

Vue.component(componentName, ComponentContext(componentFilePath));

Vue.component(componentName, ComponentContext(componentFilePath).default);

不确定默认部分。

答案 1 :(得分:0)

好,我需要在其中添加“懒惰”:

const ComponentContext = require.context('./', true, /\.vue$/i, 'lazy');

然后:

Vue.component(componentName, () => ComponentContext(componentFilePath));

答案 2 :(得分:0)

我必须在此处将问题与答案合并才能得到最终解决方案:

const ComponentContext = require.context('./', true, /\.vue$/i, 'lazy');

ComponentContext.keys().forEach((componentFilePath) => {

    const componentName = componentFilePath.split('/').pop().split('.')[0];
    Vue.component(componentName, () => ComponentContext(componentFilePath));

});

'lazy'的第三个参数添加到require.context(),并且将() => import()更改为() => ComponentContext()

我可以在“开发工具”窗格的“网络”选项卡中看到捆绑软件,当我导航到一个不呈现任何自动加载的组件的页面时,我看不到捆绑软件。

因此,我可以确定上述代码是自动加载和动态导入。我还将确认在我的项目中,我正在使用:

require.context('~/components/common', true, /\.vue$/i, 'lazy')

请注意,~/components/common的位置与./的位置不同。您的项目需求可能会有所不同。在我的系统中,~/resources/js的Webpack别名,因此我的完整路径将是./resources/js/components/common。上面的其余代码是一种算法,可以保持不变。

相关问题