webpack.config.js
I'm encountering an issue with my route URLs. When I navigate from the blog to a specific blog details page like 'blog/blog-01.html', everything works fine. However, when I click on the header to go back to the home page or any other page, my URL becomes 'blog/index.html' instead of the actual '/index.html' it should be. How can I fix this inconsistency?
const glob = require('glob');
const fs = require('fs');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyPlugin = require("copy-webpack-plugin");
const INCLUDE_PATTERN = /<include src="(.+)"\s*\/?>(?:<\/include>)?/gi;
module.exports = {
mode: 'development',
entry: './src/js/index.js',
devServer: {
static: {
directory: path.join(__dirname, 'build'),
watch: true,
},
compress: true,
port: 3000,
allowedHosts: "all",
hot: true,
liveReload: true,
open: true,
historyApiFallback: true,
},
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
clean: true,
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
},
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif|webp)$/i,
type: 'asset/resource',
generator: {
filename: (pathData) => {
// Example: Place all images in an 'images' folder in the output directory
const relativePath = path.relative(path.resolve(__dirname, 'src'), pathData.filename);
return `${relativePath.split(path.sep).join('/')}`; // Adjust the path as needed
}
}
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
{
test: /\.html$/,
loader: 'html-loader',
}
],
},
plugins: [
...generateHTMLPlugins(),
new MiniCssExtractPlugin({
filename: 'style.css',
chunkFilename: 'style.css',
}),
new CopyPlugin({
patterns: [
{ from: "./src/images", to: "images" },
],
}),
],
};
function processIncludes(filePath) {
let content = fs.readFileSync(filePath, 'utf8');
content = content.replace(INCLUDE_PATTERN, (match, p1) => {
const includePath = path.resolve(path.dirname(filePath), p1);
if (fs.existsSync(includePath)) {
return fs.readFileSync(includePath, 'utf8');
}
return '';
});
return content;
}
function generateHTMLPlugins() {
return glob.sync('./src/**/*.html').map((dir) => {
const filename = path.relative('./src', dir);
const formattedFilename = filename.split(path.sep).join('/');
var outputFilename = path.join(path.dirname(formattedFilename), path.basename(formattedFilename));
// Process includes directly in memory
const processedContent = processIncludes(dir);
return new HtmlWebpackPlugin({
filename: outputFilename,
templateContent: processedContent, // Use processed HTML content directly
favicon: './src/images/favicon.ico',
inject: 'body',
});
});
}