Answer the question
In order to leave comments, you need to log in
Building a multi-page website with webpack?
Hello, I understand webpack, for one-pagers everything is clear, there is a million information on this, but with multi-page sites everything is not so smooth
In general, the essence is this, there are pages, each page has its own styles, js
I sketched webpack, suffered, googled but could not find how to normally implement assembly for multi-pagers
Now the project is going to be like everything is ok (I know about the modes, I just didn’t write), but all the js is connected to the pages at once, i.e. for the index page, both index js and about js are loaded, styles are also not pulled
up
.
{
"name": "last-chanse",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.12.10",
"@babel/plugin-proposal-class-properties": "^7.12.1",
"@babel/preset-env": "^7.12.11",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^5.0.1",
"html-webpack-plugin": "^4.5.1",
"sass": "^1.32.5",
"sass-loader": "^10.1.1",
"style-loader": "^2.0.0",
"webpack": "^5.19.0",
"webpack-cli": "^4.4.0"
}
}
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const generateHtmlPlugin = (title) => {
return new htmlWebpackPlugin({
title,
filename: `${title.toLowerCase()}.html`,
template: `./src/pages/${title.toLowerCase()}/${title.toLowerCase()}.html`,
minify: {
collapseWhitespace: false,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true
}
});
}
const populateHtmlPlugins = (pagesArray) => {
res = [];
pagesArray.forEach(page => {
res.push(generateHtmlPlugin(page));
})
return res;
}
const pages = populateHtmlPlugins(["index", "about"]);
module.exports = {
entry: {
index: path.resolve(__dirname, './src/pages/index/index.js'),
about: path.resolve(__dirname, './src/pages/about/about.js'),
},
output: {
path: path.resolve(__dirname, './dist/'),
filename: '[name].bundle.js',
},
plugins: [
...pages,
new CleanWebpackPlugin(),
],
module: {
rules: [
// JavaScript
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
],
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question