I am new to webpack and stack oveflow too. currently I am using webpack to bundle css and script files/modules into single "bundle.js" file. Here is the code snippet (of concern) in the "index.js" file.
import loadPage from "./load-page.js";
// header element is containing three buttons home, menu, contact...
const header = document.querySelector(".header");
// Listen to the header buttons to load corresponding pages upon click of corresponding button
header.addEventListener("click", (event) => {
// Home button is clicked...
if (event.target === header.children[0]) {
loadPage("home-page")
};
else if (event.target === header.children[1]) {
loadPage("menu-page");
} else if (event.target === header.children[2]) {
loadPage("contact-page");
}
});
Here is the loadPage function in "./load-page.js" file:
function loadPage(tab) {
if (tab === "home-page") {
return import("./home-page.js");
} else if (tab === "menu-page") {
return import("./menu-page.js");
} else if (tab === "contact-page") {
return import("./contact-page.js");
}
}
export default loadPage;
here is the webpack.config.js file:
const htmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
module.exports = {
mode: "development",
entry: {
index: "./src/script-files/index.js",
},
devtool: "inline-source-map",
devServer: {
static: "./dist",
hot: true,
},
plugins: [
new htmlWebpackPlugin({
template: "./src/index.html",
}),
],
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
clean: true,
},
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};
When I click on home button, it loads correct home page, similarly rest of the pages too... But webpack also keeps previous script files in the "./bundle.js" file which were imported upon clicking home, menu button etc. buttons. But I want webpack to bundle only single script file which is being imported upon button click on run time and should discard previously added files on other buttons click. If it's not possible then atleast it should add imported script files in separate tags in "index.html" file and not in single "bundle.js" file so that I could delete them before injecting new script file. Any help please...