Ideally, you would like to be able to have Webpack manage the bundled file and its injection into the template. By default, Webpack is unable to do this, as it is only concerned with the files related to scripting. Fortunately, Webpack offers an extremely popular plugin that allows you to expand the scope of Webpack's file concerns.
The code, links, and a live example of this are available at .
Install the plugin and add it to devDependencies
of package.json
with the following:
npm install html-webpack-plugin --save-dev
First, you'll need to incorporate the plugin into package.json
if it isn't already:
[package.json] { "name": "mva-bundling", "scripts": { "start": "tsc&&webpack&& concurrently 'npm run tsc:w' 'npm run wp:w' 'npm run lite'", "lite": "lite-server", "postinstall": "npm install -S @types/node @types/core-js", "tsc": "tsc", "tsc:w": "tsc -w", "wp": "webpack", "wp:w": "webpack --watch" }, "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/core": "2.0.0", "@angular/platform-browser": "2.0.0", "@angular/platform-browser-dynamic": "2.0.0", "core-js": "^2.4.1", "reflect-metadata": "^0.1.3", "rxjs": "5.0.0-beta.12", "zone.js": "^0.6.23" }, "devDependencies": { "concurrently": "^2.2.0", "html-webpack-plugin": "^2.22.0", "imports-loader": "^0.6.5", "lite-server": "^2.2.2", "typescript": "^2.0.2", "webpack": "^1.13.2" } }
Once this module is installed, define its operation inside the Webpack config:
[webpack.config.js] var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: "./src/main.js", output: { path: "./dist", filename: "bundle.js" }, plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })] };
This specifies the output HTML file that will serve the entire application. Since the plugin will automatically generate the HTML file for you, you'll need to modify the existing one that is designated as the template:
[src/index.html] <html> <head> <title>Angular 2 Minimum Viable Application</title> </head> <body> <app-root></app-root> </body> </html>
Finally, because index.html
is now served out of the dist/
directory, you'll need to configure the development server to serve files out of there. Since lite-server
is just a wrapper for BrowserSync, you can specify baseDir
inside a bs-config.json
file, which you should create now:
[bs-config.json] { "server": { "baseDir": "./dist" } }
Webpack is very much aware of the bundle that it is creating, and so it makes sense that you would be able to maintain a reference to this bundle (or bundles) and directly pipe those paths into an index.html file. The plugin will append the scripts at the end of the body to ensure the entire initial DOM is present.