Lior Ahronovich
Lior Ahronovich

Reputation: 31

Webpack build all js files in project to multiple output files

I am trying to change my webpack config file to handle all js and jsx files in project to a multiple output files (output file name should be the entry file name). I didnt find any simple solution for that.

Upvotes: 2

Views: 1994

Answers (1)

lukas-reineke
lukas-reineke

Reputation: 3322

You can create multiple entry files, and keep the name in the output files.

entry: {
    src: './src/app.js',
    foo: './src/foo.js',
},
output: {
    path: __dirname + '/dist',
    filename: '[name].js',
},

From the documentation:

If an object is passed, each key is the name of a chunk, and the value 
describes the entrypoint for the chunk.

You can also pass a function as the entry to do more complicated things.

EDIT:
For example, this script will glob all js files in the src directory and create an entry point for each.

const glob = require('glob');

module.exports = () => {

    return {
        mode: 'development',
        entry: () => {
            return glob.sync('./src/*.js').reduce((pre, cur) => {
                pre[cur.replace(/^.*[\\\/]/, '').split('.')[0]] = cur;
                return pre;
            }, {});
        },
        output: {
            path: __dirname + '/dist',
            filename: '[name].js',
        },
    };
};

You can probably clean up the regex a bit

Upvotes: 1

Related Questions