javascript - 是否可以使用 `require.context` 为 Webpack 进行动态导入?
问题描述
我目前正在使用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);
});
};
现在我想加载Async
以require.context
通常动态导入语法如下所示:
Vue.component('search-dropdown', () => import('./search/SearchDropdownAsync'));
这将通过承诺解决并动态导入组件。
出现的问题是,当您使用时require.context
,它会立即加载(需要)组件,我无法使用动态导入。
有什么办法可以require.context
和 Webpack 的动态导入语法结合起来吗?
https://webpack.js.org/guides/code-splitting/#dynamic-imports
解决方案
还有第四个论点可以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);
});
});
推荐阅读
- python - 如何安装 Conda 3.7 环境?
- pentaho - 在 CSV 文件输入的列映射中传递变量
- mysql - 使用 isnull 和 coalesce 以两种方式重写以下错误语句
- sql - 当相关行可能不存在时从连接表中选择
- java - 无需遍历整个 List 即可找到 LinkedList 大小的方法
- python-attrs - 使用带有可调用对象的 attr.asdict() 过滤器
- javascript - serializeArray 没有选择动态创建的表单
- oracle - PL/SQL 错误引用未初始化的集合错误,即使它已初始化
- windows - 如何在 Windows 10 上为代码块 17.02 指定 MinGW64?
- ios - 我如何使用没有类型的 Rx Swift PublishRelay 仅用于 onCompleted() 事件?