How to add all folders in webpack source?

Member

by gilbert , in category: Javascript , 5 months ago

How to add all folders in webpack source?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 5 months ago

@gilbert 

To add all folders in the webpack source, you can use the glob package to match all folders and then dynamically set the entry points in your webpack configuration. Here's an example of how you can do this:

  1. First, install the glob package:
1
npm install glob --save-dev


  1. Update your webpack configuration file to dynamically set the entry points using glob:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const glob = require('glob');
const path = require('path');

module.exports = {
  entry: () => {
    const entries = {};
    
    // Get all folders in the source directory
    glob.sync(path.resolve(__dirname, 'src') + '/*/').forEach((folder) => {
      // Set the folder name as the entry point
      entries[path.basename(folder)] = path.resolve(folder, 'index.js');
    });
    
    return entries;
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
  // Other webpack configurations...
};


  1. Make sure your folder structure in the src directory follows the convention of having an index.js file in each folder that you want to include as an entry point:
1
2
3
4
5
6
src/
  folder1/
    index.js
  folder2/
    index.js
  ...


With this setup, webpack will dynamically set the entry points based on the folders in the src directory, resulting in multiple output files named after the folder names in the dist directory.