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

Webpack多入口场景下如何在输出目录中保留源目录结构?

Solution: Preserve Directory Structure & Dynamic Multi-Entry in Webpack

Great question! Let's solve both your directory structure preservation and dynamic multi-entry needs with a clean, maintainable webpack configuration.

1. Dynamic Entry Configuration

First, we'll create a function to automatically scan your src directory and generate entry points for all relevant files (e.g., .js files) while preserving their relative path structure. This eliminates the need to manually update entries as you add new files.

const fs = require('fs');
const path = require('path');

function getDynamicEntries() {
  const entries = {};
  const srcRoot = path.resolve(__dirname, 'src');

  // Recursively traverse the src directory
  function scanDirectory(dir) {
    const files = fs.readdirSync(dir);
    files.forEach(file => {
      const fullFilePath = path.join(dir, file);
      const fileStats = fs.statSync(fullFilePath);

      if (fileStats.isDirectory()) {
        scanDirectory(fullFilePath); // Dig deeper into subdirectories
      } else if (file.endsWith('.js')) {
        // Create entry key using relative path from src (without .js extension)
        const relativePath = path.relative(srcRoot, fullFilePath);
        const entryKey = relativePath.slice(0, -3); // Remove .js suffix
        entries[entryKey] = fullFilePath;
      }
    });
  }

  scanDirectory(srcRoot);
  return entries;
}

2. Output Configuration to Preserve Structure

Next, configure the output to use the entry key (which includes the relative path) as part of the filename. This ensures your dist folder mirrors the src directory structure.

3. Full Webpack Config Example

Putting it all together, here's your complete webpack.config.js:

const path = require('path');
const fs = require('fs');

// Dynamic entry generator function from above
function getDynamicEntries() {
  const entries = {};
  const srcRoot = path.resolve(__dirname, 'src');

  function scanDirectory(dir) {
    const files = fs.readdirSync(dir);
    files.forEach(file => {
      const fullFilePath = path.join(dir, file);
      const fileStats = fs.statSync(fullFilePath);

      if (fileStats.isDirectory()) {
        scanDirectory(fullFilePath);
      } else if (file.endsWith('.js')) {
        const relativePath = path.relative(srcRoot, fullFilePath);
        const entryKey = relativePath.slice(0, -3);
        entries[entryKey] = fullFilePath;
      }
    });
  }

  scanDirectory(srcRoot);
  return entries;
}

module.exports = {
  entry: getDynamicEntries(),
  output: {
    filename: '[name].js', // Uses entry key (relative path) as filename
    path: path.resolve(__dirname, 'dist'),
    clean: true, // Auto-cleans dist folder before each build (webpack 5.20+)
  },
  // Add your other configs here (module rules, plugins, devServer, etc.)
  module: {
    rules: [
      // Example: Transpile ES6+ with Babel
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader',
      },
    ],
  },
};

Key Notes:

  • For your src/js/main.js entry, this config will generate dist/js/main.js exactly as you want.
  • Any new .js files added to src (e.g., src/utils/helpers.js) will automatically be included as entries, outputting to dist/utils/helpers.js.
  • The clean: true option ensures old files are removed from dist on each build (for webpack versions <5.20, use clean-webpack-plugin instead).
  • Adjust the file extension check (file.endsWith('.js')) if you need to include other file types like .ts.

内容的提问来源于stack exchange,提问作者Seu Madruga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:24:35