'webpack-dev-server app doesn't render my html instead I get Cannot GET /

I am trying to run my javascript app with webpack dev server and I don't get my index.html back, instead I get Cannot GET / with this error inside the console GET http://localhost:8080/ 404 (Not Found). I've looked around for solutions. I tried to remove spaces from the app path and to make sure that the path inside webpack config output is the same as the one I am linking in my script tag inside index.html. But still cannot find the right answer

webpack.config.js

const path = require('path')

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'public/scripts'),
        filename: 'bundle.js'
    },
    module: {
        rules: [{
            test: /\.m?js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env']
                }
            }
        }]
    },
    devServer: {
        static: {
            directory: path.resolve(__dirname, 'public'),
            publicPath: '/scripts/'
        }
    }
}

package.json

{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev-server": "webpack-dev-server --mode development",
    "build": "webpack --mode production"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.15.7",
    "@babel/core": "^7.15.8",
    "@babel/preset-env": "^7.15.8",
    "babel-loader": "^8.2.3",
    "live-server": "^1.2.1",
    "webpack": "^5.60.0",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.3.1"
  }
}



Solution 1:[1]

Using HtmlWebpackPlugin

Packages like html-webpack-plugin simplify the creation of HTML files to serve into webpack bundles.

Usage in webpack.config.js:

const htmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/index.js",
  output: { path: `${__dirname}/build`, filename: "bundle.js" },
  resolve: { modules: ["src", "node_modules"] },
  module: {
    rules: [
      { test: /\.m?js$/, exclude: /node_modules/, loader: "babel-loader" },
    ],
  },
  plugins: [new htmlWebpackPlugin({ template: "./src/index.html" })],
};

Please note that my answer assumes that all static files are in src folder.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1