【问题标题】:Is it possible to use `require.context` to do dynamic imports for Webpack?是否可以使用 `require.context` 为 Webpack 进行动态导入?
【发布时间】:2018-10-06 21:17:00
【问题描述】:

我目前正在使用require.context 加载我的所有.vue 组件,这些组件的文件名不以Async 结尾。

const loadComponents = (Vue) => {
    const components = require.context('@/components', true, /\/[A-Z](?!\w*Async\.vue$)\w+\.vue$/);

    components.keys().forEach((filePath) => {
        const component = components(filePath);
        const componentName = path.basename(filePath, '.vue');

        // Dynamically register the component.
        Vue.component(componentName, component);
    });
};

现在我想用require.context 加载以Async 结尾的组件,这样我就不必在创建这种类型的新组件时手动添加它们。

动态导入语法通常如下所示:

Vue.component('search-dropdown', () => import('./search/SearchDropdownAsync'));

这将通过一个承诺得到解决并动态导入组件。

出现的问题是当你使用require.context时,它会立即加载(需要)组件,我无法使用动态导入。

有没有什么办法可以将require.context与Webpack的动态导入语法结合起来?

https://webpack.js.org/guides/code-splitting/#dynamic-imports

【问题讨论】:

标签: javascript webpack vue.js vue-component dynamic-import


【解决方案1】:

require.context 的第四个参数可以对此有所帮助。

https://webpack.js.org/api/module-methods/#requirecontext

https://github.com/webpack/webpack/blob/9560af5545/lib/ContextModule.js#L14

const components = require.context('@/components', true, /[A-Z]\w+\.(vue)$/, 'lazy');
components.keys().forEach(filePath => {

  // load the component
  components(filePath).then(module => {

    // module.default is the vue component
    console.log(module.default);
  });
});

【讨论】:

  • 这个解决方案太棒了!
猜你喜欢
  • 1970-01-01
  • 2021-08-01
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 2016-04-11
  • 2018-12-11
相关资源
最近更新 更多