Configure multiple entry points in Webpack.

Author
By Darío Rivera
Posted On in Webpack

In our previous article we saw What is Webpack, what is it for and how to use it. Most applications use a single entry point, that is, a single configuration file as an entry point to compile all project assets. But what happens  when you have styles or features that you use in very few pages? Little by little you end up packing everything into a single file and over time the performance of your application begins to decrease. That is why today we will see how to configure multiple entry points in Webpack.

First of all, let's see what a simple Webpack configuration file looks like.

const path = require('path');

module.exports = {
    entry: './main.js',
    output: {
        path: path.resolve(__dirname),
        filename: 'app.js'
    }
}

With this, everything in main.js will end up in app.js. But suppose we have some views like the home page that don't load many files, and other views like text editing or a dashboard where it is necessary to load many javascript and css libraries. Let's see then how to modify our webpack configuration file to improve performance a bit.

const path = require('path');

module.exports = {
    entry: {
        home: path.resolve(__dirname, 'resources/home.js'),
        editor: path.resolve(__dirname, 'resources/editor.js'),
        dashboard: path.resolve(__dirname, 'resources/dashboard.js')
    },
    output: {
        path: path.resolve(__dirname),
        filename: 'public/[name].js'
    }
}

After this, just run the command to generate the assets and you will get an output like the following:

Hash: 4c83c31e362a5abf537a
Version: webpack 4.44.2
Time: 179ms
Built at: 09/28/2020 10:34:55 PM
              Asset      Size     Chunks             Chunk Names
public/dashboard.js  3.93 KiB  dashboard  [emitted]  dashboard
   public/editor.js  3.91 KiB     editor  [emitted]  editor
     public/home.js   3.9 KiB       home  [emitted]  home
Entrypoint home = public/home.js
Entrypoint editor = public/editor.js
Entrypoint dashboard = public/dashboard.js
[./resources/dashboard.js] 99 bytes {dashboard} [built]
[./resources/editor.js] 99 bytes {editor} [built]
[./resources/home.js] 99 bytes {home} [built]

Now you can modify your views and load exactly what they need. See you next time.


Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.