A webpack bundler template for HTML, CSS, JS with image loaders, eslint, and prettier. Steps for basic setup
Initialize a package.json file using
npm init -y
Install webpack
and webpack-cli
package
npm install --save-dev webpack webpack-cli
Create a src
directory for your source code files and create your necessary files in it & Create an assets
directory in src
directory for adding your media
Note
Here, index.html, style.css, script.js are used as starter files
mkdir src && touch src/index.html src/style.css src/script.js && makdir src/assets
Install html-webpack
for handling html and style-loader
, css-loader
npm install --save-dev html-webpack-plugin style-loader css-loader
Create config file webpack.config.js
touch webpack.config.js
Add following configurations to it
Important
If you change the starter filenames, make sure to change the paths on the line commented as IMPORTANT
// for handling html file
const HtmlWebpackPlugin = require("html-webpack-plugin");
// default import
const path = require("path");
module.exports = {
// default configuration object
mode: "development",
entry: "./src/script.js", // IMPORTANT
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist"),
clean: true,
},
// for handling html file
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html", // IMPORTANT
}),
],
// for handling css, html images & js images
module: {
rules: [
{
// for loading css imported in js files
test: /\.css/i,
use: ["style-loader", "css-loader"],
},
],
},
};
For loading images in html install html-loader
& also add rules in configuration file and for js just add the rules (append these rules to the existing ones)
npm install --save-dev html-loader
module: {
rules: [
{
// for loading images in html files
test: /\.html$/i,
loader: "html-loader",
},
{
// for loading images in js files
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: "asset/resource",
},
],
},
For auto-reload on save, ease-in-debugging, source-map, install webpack-dev-server
and add the required rules in the configuration file
npm install --save-dev webpack-dev-server
// for auto-reload, source-map, and watching for html file
devtool: "eval-source-map",
devServer: {
watchFiles: ["./src/template.html"],
},
Run the following command and go to localhost:8080
npx webpack serve --open