Bundling our JavaScript for distribution using Webpack

In a web browser context, all JavaScript code that needs to be executed by the end user must ultimately be served through a <script> tag. While making our game, eventually we will have to split our code into multiple files, and it's not viable to use <script> tags for each of them. This makes it necessary to have a build (or bundling) step, where all of our small JavaScript files are merged into a single file, which is then served to our players.

The tool we'll be using is called Webpack, and it can be easily installed using npm. Type the following command in the terminal to install Webpack:

npm install -D webpack webpack-cli

Note the difference in the command syntax from the previous section when we installed http-server. The first difference is the -D parameter, which means that Webpack is a development dependency and won't be included in the code that the user sees. In addition, we are installing two packages at once, both webpack and webpack-cli. Webpack is the tool that will do the actual bundling operation, while Webpack CLI allows us to initiate the bundling process using commands typed in the terminal.

Once Webpck is installed, there's one final step before we can use it. Let's create a small configuration file with the webpack.config.js name in the project's root directory and place the following content in it:

const path = require('path');

module.exports = {
    entry: path.resolve(__dirname, 'src', 'index.js'),
    mode: 'development',
    output: {
    path: path.resolve(__dirname),
    filename: './bundle.js',
    },
};

What this config file does is instruct Webpack to take the src/index.js file an whatever is imported in it, bundle it into one single file, and put the output file called bundle.js in the root directory of our project.

At the moment we don't have a src directory, so let's go ahead and create it. In the src directory let's also create a file called index.js and put the following code in it:

const greeting = "Hello Webpack!";
alert(greeting);

We're finally ready to try everything out! Try out the following command:

npx webpack

If the command ran successfully, we should be able to navigate to http://localhost:8080 on the browser. If we get something similar to the screenshot below, then the whole process was a success:

This screenshot from Google Chrome shows the code bundled by Webpack has been successfully added to our page

In the next chapter, we'll get glimpses of our game by displaying shapes on the screen while also learning about the fundamentals of computer graphics.

Next: Publishing your JavaScript code and site to GitHub Pages