是否可以使用 `require.context` 为 Webpack 进行动态导入? [英] Is it possible to use `require.context` to do dynamic imports for Webpack?
问题描述
我目前正在使用 require.context
加载我所有的 .vue
组件,这些组件的文件名不以 Async
结尾.>
I am currently using require.context
to load all my .vue
components that do not have a filename ending with 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
这样我就不必在创建新组件时手动添加它们这种类型.
Now I want to load the my components that end with Async
with require.context
so I don't have to manually add them whenever I create a new component of this type.
通常动态导入语法如下所示:
Normally the dynamic import syntax would look like this:
Vue.component('search-dropdown', () => import('./search/SearchDropdownAsync'));
这将通过承诺解决并动态导入组件.
This will get resolved with a promise and import the component dynamically.
出现的问题是,当你使用require.context
时,它会立即加载(需要)组件,而我无法使用动态导入.
The problem that occurs is that when you use require.context
, it will immediately load(require) the components and I am unable to use the dynamic import.
有没有什么办法可以把require.context
和Webpack的动态导入语法结合起来?
Is there any way to combine require.context
with the dynamic import syntax of Webpack?
https://webpack.js.org/guides/code-splitting/#dynamic-imports
推荐答案
require.context
有第四个参数可以帮助解决这个问题.
There is a fourth argument for require.context
which can help with this.
https://webpack.js.org/api/module-methods/#需要上下文
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);
});
});
这篇关于是否可以使用 `require.context` 为 Webpack 进行动态导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!