You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用require.context后如何动态加载Vue组件并排除指定文件?

I’ve run into this exact scenario before—trying to use require.context for bulk component loading but needing to carve out specific files for async dynamic imports. Let’s break down how to fix this properly:

1. Use a Negative Lookahead Regex to Exclude Files (Static Rule)

If your async components follow a consistent naming pattern (like starting with Async, or living in an async subdirectory), you can directly exclude them in the require.context regex using a negative lookahead. This tells Webpack to skip those files during the initial bulk load, leaving them available for true async import.

Example: Exclude components starting with Async

// Sync-load all non-Async Vue components
const syncComponents = require.context(
  './components',
  true, // include subdirectories
  /^((?!Async).)*\.vue$/ // regex: matches .vue files NOT containing "Async"
);

// Register sync components normally
syncComponents.keys().forEach(key => {
  const componentName = key.split('/').pop().replace(/\.vue$/, '');
  Vue.component(componentName, syncComponents(key).default);
});

// Async-load only the excluded Async components
const asyncComponents = require.context(
  './components',
  true,
  /Async.*\.vue$/ // regex: matches only .vue files starting with "Async"
);

asyncComponents.keys().forEach(key => {
  const componentName = key.split('/').pop().replace(/\.vue$/, '');
  // Use dynamic import for true async loading
  Vue.component(componentName, () => import(`./components/${key.slice(2)}`));
  // key starts with "./", so slice(2) removes that prefix for the import path
});

Example: Exclude an entire subdirectory (e.g., components/async)

Adjust the regex to skip any file under the async folder:

const syncComponents = require.context(
  './components',
  true,
  /^((?!\/async\/).)*\.vue$/
);

2. Dynamic Filtering (For Non-Static Exclusion Rules)

If you can’t hardcode a regex (e.g., your exclusion list is dynamic or based on external conditions), you can first fetch all components with require.context, then manually filter which ones to load sync vs async.

// Get all Vue components first
const allComponents = require.context('./components', true, /\.vue$/);

// Define your list of files to exclude (async candidates)
const asyncFileList = ['CheckoutAsync.vue', 'ProfileAsync.vue'];

// Load sync components (exclude the async list)
allComponents.keys().forEach(key => {
  const fileName = key.split('/').pop();
  if (!asyncFileList.includes(fileName)) {
    const componentName = fileName.replace(/\.vue$/, '');
    Vue.component(componentName, allComponents(key).default);
  }
});

// Load async components (only the ones in the exclusion list)
asyncFileList.forEach(fileName => {
  // Find the full path key for the file (handles subdirectories)
  const matchingKey = allComponents.keys().find(key => key.endsWith(`/${fileName}`));
  if (matchingKey) {
    const componentName = fileName.replace(/\.vue$/, '');
    Vue.component(componentName, () => import(`./components/${matchingKey.slice(2)}`));
  }
});

Key Notes

  • Webpack statically analyzes require.context, so you can’t dynamically generate the regex (it needs to know which files to bundle at compile time). Dynamic filtering (method 2) works because we first fetch all files, then split them post-fetch.
  • The dynamic import syntax (() => import(...)) will trigger Webpack to split those async components into separate chunks, which are loaded only when the component is first used—exactly the async behavior you want.

内容的提问来源于stack exchange,提问作者Stephan-v

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:25:21