Basic webpack setup with index.html automatically generated to dist directory
Table of contents
- How we will automatically create a index.html file in this guide
- Install the yarn/npm dependencies
- Create a basic
webpack.config.js
file - Create your JS files (app.js)
- Create some yarn scripts to help run and build your app
- Use webpack to build your JS assets and it will create a .html file with all assets imported in
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
webpack.config.js
file
Create a basic 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!';
document.body.appendChild(el);
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!
Part of my webpack series
- javascript Set up babel loader with Webpack guide (how to use babel loader)
- typescript Guide to setting up Typescript with Webpack
- javascript How to set up style loader and css loader with webpack, to include CSS style files when building your JS app
- javascript Basic webpack setup with index.html automatically generated to dist directory