Dynamically create Webpack 5 Entries from array

40 Views Asked by At

I would like to add additional entries in webpack.config.js from an array with Webpack 5. here is the array:

const unitTest = [ { name: 'bootloader' }, { name: 'levenshtein' } ]

I wrote the following code to append the additional entries from the array.

entry: {
    main: ['./src/js/index.js'],

    ...unitTests.map((test) => {
      let newEntry ={};
      newEntry[`${test.name}`] = [`./src/unit-test/${test.name}/index.js`];
      return newEntry;
    }),
    
  },

The problem is that the map() function returns an array, and my entries become something like:

{
  '0': { bootloader: [ './src/unit-test/bootloader/index.js' ] },
  '1': { levenshtein: [ './src/unit-test/levenshtein/index.js' ] },
  main: [ './src/js/index.js' ],
}

Of course, Webpack isn't happy. I can't figure out how the append new fields propertly to the entry object?

1

There are 1 best solutions below

0
mandy8055 On BEST ANSWER

One way is to use reduce() rather than using map() to ahieve your desired result. Something like:

const unitTests = [ { name: 'bootloader' }, { name: 'levenshtein' } ];

const entries = unitTests.reduce((acc, test) => {
  acc[`${test.name}`] = [`./src/unit-test/${test.name}/index.js`];
  return acc;
}, {});

module.exports = {
  entry: {
    main: ['./src/js/index.js'],
    ...entries
  },
  // other webpack configs
};

const unitTests = [ { name: 'bootloader' }, { name: 'levenshtein' } ]

const entries = unitTests.reduce((acc, test) => {
  acc[`${test.name}`] = [`./src/unit-test/${test.name}/index.js`];
  return acc;
}, {});

const entry =  {
    main: ['./src/js/index.js'],
    ...entries,
  };
  
console.log(entry);