A browser needs an HTTP server to load a web application's HTML and JavaScript bundle. Webpack Development Server (WDS) serves those files during development and reloads the browser when changed code produces a new bundle. Install it in the `webapp` folder with `npm install --save-dev webpack-dev-server@4.13.1`. section 16.4
Listing 16.11 Server configuration in the webpack.config.js file in the webapp folder
module.exports = {
mode: "development",
devtool: "inline-source-map",
entry: "./src/index.ts",
output: { filename: "bundle.js" },
resolve: { extensions: [".ts", ".js"] },
module: {
rules: [
{ test: /\.ts/, use: "ts-loader", exclude: /node_modules/ }
]
},
devServer: {
static: "./assets",
port: 4500
}
};
In `webpack.config.js`, `devServer.static` points to `./assets` for files other than the bundle, and `port` sets the HTTP port to 4500. The existing entry point and TypeScript loader still determine what webpack bundles. section 16.4
Listing 16.12 The contents of the index.html file in the assets folder
<!DOCTYPE html> <html> <head> <title>Web App</title> <script src="bundle.js"></script> </head> <body> <div id="app">Web App Placeholder</div> </body> </html>
Put `index.html` in `webapp/assets`. Its `script` element requests `bundle.js`, which contains the application's JavaScript. section 16.4
Run `npx webpack serve` in `webapp`, then open `http://localhost:4500`. WDS builds the bundle and serves it from memory rather than writing it to `dist`. It also puts webpack in watch mode: changing a code file triggers another build and a browser reload. For example, add another `console.log` to `src/index.ts` and check the browser console after the reload. section 16.4
The server remains useful as the application grows: webpack can add CSS to the bundle through `css-loader` and `style-loader`. A `package.json` script can run `webpack serve` alongside a separate `json-server` web service using `npm-run-all`. Stop WDS before changing development packages or configuration. Do not use it to host a production application; its generated bundles include development features such as automatic reloading. section 16.6.1 section 17.1 section 19.3
