Basic webpack setup with index.html automatically generated to dist directory

November 13, 2020

This is a guide to initially setting up Webpack, to compile your JS assets and to automatically generate a HTML file which includes the asset <script> tags.

This is part of a series to guides to using Webpack.

How we will automatically create a index.html file in this guide

We will use HtmlWebpackPlugin in this guide:

The HtmlWebpackPlugin simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation. You can either let the plugin generate an HTML file for you, supply your own template using lodash templates, or use your own loader.

Install the yarn/npm dependencies

Install the html-webpack-plugin, webpack and webpack-cli packages:

yarn init
yarn add -D html-webpack-plugin webpack webpack-cli

Create a basic webpack.config.js file

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

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Your amazing app!',

Create your JS files (app.js)

Create a directory src, and inside that create a file (src/index.js)

console.log("Hello, world!");

const el = document.createElement('div');
el.innerText = 'Hello world!';

Create some yarn scripts to help run and build your app

Inside your package.json, update the "scripts" part (you may need to add it) with the "scripts" part below:

  "name": "webpack-example",
  "main": "index.js",
  "devDependencies": {
    "html-webpack-plugin": "^4.5.0",
    "webpack": "^5.4.0",
    "webpack-cli": "^4.2.0"
  "scripts": {
    "dev": "webpack --mode development",
    "build": "webpack --mode production"

Use webpack to build your JS assets and it will create a .html file with all assets imported in

Run yarn dev, and hopefully after a few sections you will see a dist directory was created with your JS files included. There will also be a index.html, which has <script src="index.js">.

Hopefully you are now all set and this guide to setting up webpack along with using html-webpack-plugin to automatically generate your index.html file worked!