I’m working on a project with a Webpack where I am trying to dynamically generate the content of a page using JavaScript. However, when I load the page, the content does not appear. Only the navigation bar is visible, and I can’t see any content being added to the #content div.
Here’s a breakdown of what I’ve tried:
/project-folder
/dist
/node_modules
/src
/index.js
/greeting.js
/template.html
.gitignore
package.json
webpack.config.js
index.js
import { generatePage } from "./greeting";
generatePage()
greeting.js
export function generatePage(){
const header=document.createElement("h1")
const image=document.createElement("img")
const headertwo=document.createElement("h2")
const paragraph=document.createElement("p")
header.textContent = "Welcome to Our Restaurant!";
headertwo.textContent = "Best Dishes Served Fresh!";
paragraph.textContent = "Our restaurant offers a variety of delicious meals made with love and care.";
const container=document.querySelector("#content")
container.appendChild(header)
container.appendChild(image)
container.appendChild(headertwo)
container.appendChild(paragraph)
}
template.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Restaurant Page</title>
</head>
<body>
<header>
<nav>
<button type="button">Home</button>
<button type="button">Menu</button>
<button type="button">About</button>
</nav>
</header>
<div id="content">
</div>
webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist"),
clean: true,
},
devtool: "eval-source-map",
devServer: {
watchFiles: ["./src/template.html"],
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/template.html",
}),
],
module: {
rules: [
{
test: /.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /.html$/i,
loader: "html-loader",
}
],
},
};
What I’ve Tried:
-
I’ve added console.log statements in index.js and greeting.js to confirm that the scripts are running, but I don’t see any logs in the browser console.
-
I made sure the Webpack development server is running and the page is reloading correctly (npx webpack serve).
-
The page loads, but only the navigation bar is visible, and none of the content (like the header, image, and paragraph) is being added to the #content div.
What I Expect:
I expect the content to be dynamically generated and added to the #content div after the page loads, but it’s not appearing. The log messages also don’t show up in the console.
