I've been grappling with this issue for the past couple of days and haven't been able to find a solution. I've tried following a few steps from Stack Overflow, but they didn't work for me. Additionally, all the related questions were quite old, dating back 3-4 years.
Within my build folder, I have files named bundle.js, bundle.css, and index.html. The index.html file contains
<link href="bundle.css">
and <script src="bundle.js">
.
My goal is to inline both bundle.js and bundle.css into the index.html using webpack. However, I'm encountering two issues:
- The JS file gets inlined, but the index.html still references
script src="bundle.js"
- The CSS file doesn't get inlined at all and isn't showing up in the
dist
folder
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>Internal site</title>
<script src='bundle.js'></script>
<link rel='stylesheet' href='bundle.css'>
</head>
<body></body>
</html>
webpack.config.js
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const HtmlInlineCSSWebpackPlugin = require('html-inline-css-webpack-plugin').default;
const HtmlInlineScriptWebpackPlugin = require('html-inline-script-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, './internal_site/public/'),
entry: {
main: './bundle.js', // Entry JavaScript file
},
output: {
filename: '[name].js', // Output JS bundle
path: path.resolve(__dirname, 'dist'), // Output directory
clean: true, // Clean output directory before build
},
module: {
rules: [
{
test: /\.css$/, // Match CSS files
use: [
'style-loader', // Extract CSS into separate files
'css-loader', // Resolve CSS imports
],
},
],
},
plugins: [
new HTMLWebpackPlugin({
template: './index.html', // Path to your index.html
inject: 'body', // Inject scripts into the body
minify: {
collapseWhitespace: true, // Minify HTML
removeComments: true, // Remove comments
},
}),
new HtmlInlineCSSWebpackPlugin(), // Inline CSS into <style> tags
new HtmlInlineScriptWebpackPlugin(), // Inline JavaScript into <script> tags
],
optimization: {
minimize: true,
minimizer: [
new (require('terser-webpack-plugin'))({
extractComments: false, // Remove comments
}),
],
},
mode: 'production',
};
Versions:
"webpack": "^5.97.1",
"webpack-cli": "^6.0.1"