Unable to incorporate JavaScript and CSS into the webpage using webpack

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:

  1. The JS file gets inlined, but the index.html still references script src="bundle.js"
  2. 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"

Answer №1

If you're looking to easily include JS and CSS directly into your HTML, the html-bundler-webpack-plugin is a great tool.

This plugin enables you to define your source JS and SCSS/CSS files directly within your HTML file. For example, if you're importing CSS in your JS file, only the source JS file needs to be defined in your HTML.

Here's an example of what your source JS file (./bundle.js) might look like:

import './style.css';

console.log('>> bundle');

You can place the script tag anywhere in your HTML - whether it's in the head or body. The JS will be automatically inlined at that exact spot in the generated HTML, without needing to specify the JS file in Webpack entry.

In your index.html file, it would look something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Internal site</title>
    <link rel='stylesheet' href='./bundle.css'>
</head>
<body>
  <h1>Hello World!</h1>
  <script src="./bundle.js"></script>
</body>
</html>

The Html Bundler Plugin simplifies the process of inlining CSS and JS into your HTML without extracting comments, eliminating the need for additional plugins and loaders like terser-webpack-plugin.

  • html-webpack-plugin
  • html-inline-css-webpack-plugin
  • html-inline-script-webpack-plugin
  • style-loader
  • and more listed here

For more information and recipes on how to inline CSS, JS, and all resources into a single HTML file using the Html Bundler Plugin, check out these links:

P.S.

If you need help setting up your project, feel free to create a small repo on GitHub and I can assist with the configuration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue where the P3D sketch does not function properly when running

Currently, I am in the process of converting a project I developed in Processing [Java Mode] to an online platform for web viewing. The project involves P3D rendering to showcase a 3D environment that allows for rotation and manipulation of three data sets ...

The equation of Gulp, wiredep, browsersync, and bower results in missing components

I am currently working with a build/dist folder structure, having a bower_components folder at the root of my app directory. Is there a way to configure browserSync so that my web browsers can properly load the CSS and JS resources from Bower? When I set ...

Executing Concurrent API Requests in React

I have a project where I am working on an app that involves receiving data from an API. The process includes making two fetch requests to the same API - the first call retrieves information needed for the second call. fetch(req) .then((response)=>( ...

Exploring the world of Next.js version 9.3 and beyond with the exciting addition

As a beginner with Next.js, I am seeking guidance on utilizing getStaticPaths and getStaticProps within catch-all routes. Many blog starters for Next.js 9.3+ focus on single-level blog posts (such as /posts/post-1.md, /posts/post-2.md, etc.), but I am stru ...

What is the best way to use pattern matching to specifically match IDs while ensuring that the variable number aligns without needing to manually code every potential option?

I have recently acquainted myself with Jquery selectors and they are proving to be very useful. The issue I am facing currently is that all of my variable names follow similar patterns of starting and ending. The IDs are generated from elsewhere, and I am ...

The issue of duplicate CSS arising during the compilation of SASS into a single CSS file with G

Just getting started with Stack Overflow and Gulp (using version 3.9.1). My goal is to compile all of my scss files into a single css file for my website. Here's what I have in my gulpfile so far: var gulp = require('gulp'); var sass = requ ...

When jQuery updates the content, the div content disappears temporarily

I am currently using jQuery to generate HTML by fetching data from a JSON file. Below is the code snippet where I create the HTML: $(document).ready(function () { $('#searchForm').submit(function () { var entry= $("#searchFo ...

What is causing the Link component in react-router-dom to not accept the className props?

Here's a customized component called PageLink: export const PageLink: React.FC<IProps> = ({ id, question, searchBy }) => { return ( <Link to={{pathname: `results/${id}`, search: `?sortBy=${searchBy}`}} className={styles.PageLink}> ...

How to access a global variable within an Angular application

Using node express and angular, I have set up a route in my express app.js where I pass a variable to the rendered page: app.get('/test', function(req, res){ res.render('test', { user: 12345 }); }); Within my 'test' view, ...

Why does a jQuery function fail to execute when it contains Ruby on Rails code within a partial?

I'm currently working on implementing pagination with jQuery using the will_paginate gem. Everything works fine without JavaScript, but I'm running into some issues when trying to incorporate AJAX pagination. I've followed a tutorial on Rail ...

Retrieve the HTML source code using AngularJS through an HTTP GET request

I came across a thread in the forum discussing a similar issue but unfortunately, it didn't have any answers. Let me explain my problem - I'm trying to validate a form using AngularJS and connect it by sending an HTTP request on submit. In my log ...

Tips for using "if not equal" with multiple items in JavaScript

I have a simple question that I've been thinking about. Is there a way to accomplish the following: If i is not equal to 1, 2, or 3, then alert('yes'); Can we achieve it using the following code: if (!(i==1&2&3)) { alert('yes ...

Perfecting the Radio Button Selection (because why not?)

Struggling to round the outer corners of three inline squared radio buttons with unique IDs. Need help fixing my CSS syntax - I can get each button to individually round its corners, but not just radio1 and radio3's outer corners. Check out the issue ...

Enhancing your JQuery Select2 plugin by incorporating a Checkbox feature

I am currently utilizing the jQuery select2 plugin to enable multiple selections. My goal is to incorporate a checkbox for each selectable option. Depending on whether the checkbox is checked or unchecked, the dropdown option should be selected accordingl ...

Distinguishing the clicked stack in a grouped stacked bar chart (using Chart.js) - deciphering the mystery

I have implemented a bar chart similar to the image shown. The chart consists of two stacks grouped together, each stack containing multiple datasets. This implementation involves the use of Vue.js and vue-chartjs. https://i.sstatic.net/OOex2.jpg For han ...

Press on any two table cells to select their content, highlight it, and save their values in variables

I have a table retrieved from a database that looks like this (the number of rows may vary): |Player 1|Player 2| ------------------- |Danny |Danny | |John |John | |Mary |Mary | My goal is to select one name from each Player column and sto ...

Setting up Next.js configuration for JSX file type

I have developed a Next 13 application and installed the package @viral-loops/widgets. However, upon running the application, I encountered the following error: error - ./node_modules/@viral-loops/widgets/dist/react/Widget.jsx Module parse failed: Unexpec ...

Encountered difficulties displaying React application within ASP.NET Core startup program

Introduction In my quest to merge an existing React app with an ASP.NET Core web app, I aimed to launch the ASP.NET Core project and display the React app just as if I were running npm start from the ClientApp directory. Initial Setup To explore this in ...

Shifting divs to different positions upon clicking

I am currently working on a project where I have three divs in a container positioned next to each other. My goal is to make them change their positions when clicked. For example, clicking on the left div should move it to the center position. Here is my p ...

The Art of Using Ajax and jQuery in Joomla

Hello! I am currently facing an issue with the custom pagination for a Joomla component. I am attempting to create a list of user articles, displaying 3 posts per page without refreshing the webpage. After hours of searching for a solution, I decided to i ...