I have been dealing with this problem for past 2 days and couldn’t resolve it. I tried few other steps posted in stackoverflow but couldn’t make it work and all the questions were 3-4 years old as well.
I have a build folder containing – bundle.js, bundle.css and index.html. The index.html contains <link href="bundle.css">
and <script src="bundle.js">
.
I am trying to inline the bundle.js and bundle.css into index.html using webpack. I am facing two problems:
- JS file gets inlined but the index.html still has
script src="bundle.js"
- CSS does not get inlined at all and neither does it appear in
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"