UI/UX Design

How to configure webpack.config.js

In this article I’ll show you how to configure the webpack.config.js file which will help you take advantage of the Webpack’s powerful features.

Webpack is fed a configuration object which will help you configure different Webpack parameters and the modules or plugins you want to use. Depending on your usage of Webpack there are two ways to pass this configuration object. One of them is using a webpack.config.js file which should export the configuration object:

  
  
module.exports = {
    // configuration
};
  

The first thing we will achieve is to setup a simple boilerplate that will allow us to run the webpack command in terminal without writing the input/output file name.

Let’s get started

Create a new project that will contain:

index.html

  
  
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF8">
    <title>Webpack.config.js configuration</title>
  </head>
  <body>
  </body>
</html>
  

 
app.js

    
    
  alert('This is Webpack');
  

 
webpack.config.js

  
  
module.exports = {
  entry: './app.js',
  output: {
    filename: 'app.bundle.js'
  }
}
  

 
The config object above contains 2 important properties. The first one is entry which contains the path to the file which should be compiled by Webpack. The second one is output and is an object with a property filename where you can set the name of the compiled file.

If you followed this Webpack tutorial which I wrote a while ago, you saw that in order to compile a javascript file you would have to specify the entry and output properties in the Webpack command like:

  
  
webpack app.js app.bundle.js
  

 
Now, because these are set in the webpack.config.js, all you need to run in the terminal is:

  
  
webpack
  

 
If you don’t want to keep running the Webpack command everytime you change the file, you can modify the config and set the watch property to true. This will tell Webpack to watch the files for any changes and compile them automatically.

  
  
module.exports = {
  entry: './app.js',
  output: {
    filename: 'app.bundle.js'
  },
  watch: true
}
  

 
Now start webpack

  
  
webpack --watch
  

That’s all for the moment. In the next article I will show you how to use transpilers like Babel and plugins to help you with web development.

Andy

UI/UX Designer & Front-end Engineer based in Dublin currently working @IBM.
I write about: UI/UX Design, Javascript, HTML, CSS, React JS and React Native

Add comment