UI/UX Design

How to compile multiple javascript files with Webpack

In this post I will show you how to compile multiple javascript files into a single javascript file using the module.exports functionality from Webpack.

The advantage of this approach is that you won’t have to import all the libraries one by one inside the html page because they are all compiled into one single javascript file and they’re used only when needed. This might not sound like a big deal but when you’re writing modular applications the code will get messy very fast. I worked on projects when I had to use over 15 javascript libraries such as AngularJs, jQuery, Angular Route etc and Webpack definitely helped.

To show you how to do this, I will start with a very simple example.

1. Create a file called subtracting.js

  function subtracting(x, y) {
    return x - y;
  }

 

2. Create a file called adding.js

  function adding(x, y) {
    return x + y;
  }

 

3. Create a file called main.js

Here we are just using the 2 files we just created

  console.log("Adding: " + adding(3, 2));
  console.log("Subtracting: " + subtracting(3, 2));

 

4. Create a file called index.html

Now if you would have to print out those 2 logs, your html file will look something like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <script src="adding.js"></script>
    <script src="subtracting.js"></script>
    <script src="main.js"></script>
  </body>
</html>

 

This already looks messy and there are only 3 javascript files. Let’s update these files and use Webpack instead.

All you have to do is to use the function module.exports from Webpack to export the functions you want to be compiled into a single file.

1. Your subtracting.js file will look like:

  function subtracting(x, y) {
    return x - y;
  }

  module.exports = subtracting;

 

2. Your adding.js file will look like:

  function adding(x, y) {
    return x + y;
  }

  module.exports = adding;

 
To be able to run these functions in main.js, we’ll have to “require” adding.js and subtracting.js files inside main.js so it will look like:

  var adding = require('./adding');
  var subtracting = require('./subtracting');

  console.log("Adding: " + adding(3, 2));
  console.log("Subtracting: " + subtracting(3, 2));

 

Compile this file into bundle.js as I wrote here using the command:

  
  
webpack main.js bundle.js
  

 

When this file is compiled, it will automatically know that it needs subtracting.js and adding.js files and will only export the functions you wanted.

To test if this works, update your index.html to:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <script src="bundle.js"></script>
  </body>
</html>

Now if you check your developer console you should see the 2 logs.

Add comment