Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add wildcard mapping in entry of webpack

People also ask

How does webpack bundling work?

Webpack is a module bundler. It takes disparate dependencies, creates modules for them and bundles the entire network up into manageable output files. This is especially useful for Single Page Applications (SPAs), which is the defacto standard for Web Applications today.

What is require context?

require. context is a special feature supported by webpack's compiler that allows you to get all matching modules starting from some base directory.


Having one or few entry points should be enough for most of use cases, but if you really want to bundle up all files from directory you can use following:

As explained here: https://github.com/webpack/webpack/issues/370

var glob = require("glob");
// ...
entry: glob.sync("./src/scripts/*.js")

Webpack is expecting a list of files for the entry configuration, not a glob pattern.

You'll have to list the files manually, or automatically with this code snippet

var fs = require('fs'),
    entries = fs.readdirSync('./src/scripts/').filter(function(file) {
        return file.match(/.*\.js$/);
    });

and then pass it to webpack's config.


The entry value should resolve to a specific file, or a list of specific files.

From the webpack docs:

If you pass a string: The string is resolved to a module which is loaded upon startup.

If you pass an array: All modules are loaded upon startup. The last one is exported.

If you are simply trying to define one module, edit your entry value to point to your main application file and then require other modules from that.

If you really want to bundle all files from a directory, see arseniews answer


I had some problems with file paths in Webpack 2.4.1, so made this. In addition to multiple entries, this also creates multiple .html files.

const HtmlWebpackPlugin = require('html-webpack-plugin');
const fs = require('fs');

function getEntries (){
    return fs.readdirSync('./src/pages/')
        .filter(
            (file) => file.match(/.*\.js$/)
        )
        .map((file) => {
            return {
                name: file.substring(0, file.length - 3),
                path: './pages/' + file
            }
        }).reduce((memo, file) => {
            memo[file.name] = file.path
            return memo;
        }, {})
}

const config = {
    entry: getEntries, 
    output: {
        path: resolve('./public'),
        filename: '[name].js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'My App',
            filename: '[name].html',
            template: './pages/_template.html'
        })
    ]
}