gpt4 book ai didi

javascript - 是否可以使用 `require.context` 为 Webpack 进行动态导入?

转载 作者:搜寻专家 更新时间:2023-10-30 22:17:24 24 4
gpt4 key购买 nike

我目前正在使用 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'));

这将通过 promise 得到解决并动态导入组件。

出现的问题是当你使用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);
});
});

关于javascript - 是否可以使用 `require.context` 为 Webpack 进行动态导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50038473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com