What methods does webpack use to minify CSS links within HTML code?

As a newcomer to webpack, I am looking to compress and reference linked CSS files in HTML.

Below is the code snippet I am working with:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"><
    <title>demo</title>;
    <link rel="stylesheet" href="../src/common.css">    
</head>

<body>
  <div class="common-red">
  hello;
  </div>
 <script src="main.js"></script>
</body>
</html>

js file:

import "common.css"



This is my profile setup:

webpack.config.js:


const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    entry: "./src/index.js",
    output:{
        filename: 'bundle.js',
        path: path.resolve(__dirname,'dist')
    },
    module:{
        rules:[
            {
                test:/\.css$/,
                use:[
                    MiniCssExtractPlugin.loader,
                    "style-loader",
                    'css-loader'
                ]
            },
            {
                test:/\.(png|svg|jpg|gif)$/,
                use:[
                    'file-loader'
                ]
            },
            {
                test:/\.(html)$/,
                use:{
                    loader: "html-loader",
                    options:{
                        attrs:['img:src']
                    }
                }
            }
        ]
    },
    plugins:[
        new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename: "[id].css"
        })
    ],
    optimization: {
        splitChunks: {
          cacheGroups: {
            styles: {
              name: 'styles',
              test: /\.css$/,
              chunks: 'all',
              enforce: true
            }
          }
        }
      }
}

I have been attempting to compress the linked CSS code within the HTML document without success. However, I can package the CSS file within the JavaScript file. Any ideas on how to achieve this?

Expectations:

To successfully package the linked CSS file within the HTML document and reference it accordingly.

Your assistance is greatly appreciated!

Thank you.

Answer №1

To enable MiniCssExtractPlugin, make sure to import your CSS file into your JavaScript file.

Here is an example:

main.js

import "css/styles.css";

import "jquery/dist/jquery.min.js";
import "bootstrap/dist/js/bootstrap.min.js";

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

Whenever I try to import a directory that contains modules, Webpack encounters an error

I am currently in the process of developing a small npm library to streamline API interaction. Here is an overview of my folder structure... dist/ index.js src/ index.js endpoints/ endpoint1.js package.json webpack.config.js Inside my src/index ...

Aligning a div within another div and organizing its elements

Hey everyone, I'm struggling with centering a div that contains two Tumblr posts columns, as shown in the screenshot linked below. I really want it to be centered on the page where there is no sidebar present. Additionally, I'm hoping to get the ...

What measures can be taken to prevent the reloading of a subfolder within the same parent in the Fuel

var DataSourceTree = function (options) { this.source = options.source; } DataSourceTree.prototype = { data: function (options, callback) { var self = this; var ...

Guide to horizontally aligning a div with a dynamic width in the center

After extensive research, I discovered that setting a width allows you to center a div using margin: 0 auto along with left: 0;, right: 0, and position: absolute. However, all the examples I found had a specified width. In my specific case, I need to cent ...

What is the best way to implement two events in onPress using React Native?

I'm trying to implement the UploadB function and toggle the modal visibility using setModalVisible(!modalVisible)... However, my attempts so far have not been successful. const UploadB = useCallback(() => { dispatch({ type: ADD_P ...

What is the best way to create scrollable content inside a container?

To accommodate more fields within my fixed-position container, I need to increase its height. However, instead of doing this, I believe adding a scroll bar to the container and making its contents scrollable would be a better solution. The challenge now i ...

I attempted to update the text on an HTML page using the content of "conetnt", however, it was unsuccessful

.custom-div { outline: none !important; width: 450px; margin: auto; background-color: #ccc !important; text-indent: -9999px;} .custom-div::before{content: 'sample';color: black;} ...

Highlighted Navigation Options

When visiting , take note of the top navigation bar. The background color on this page is white, but as you navigate to other pages, the tab changes to a different color. How can you modify this behavior and change the class? Is PHP or jQuery necessary f ...

Error code 405: The POST method is not compatible with submitting multiple forms using JavaScript code simultaneously

Having multiple forms on a single page that are all submitted using the same JavaScript code presents some challenges. <form class="form" id="cancelchallenge1" method="POST" action="{{action('ChallengeController@cancelChallenge')}}"> <i ...

How to select specific folders for packaging with asar within an Electron app

I'm currently working on an Electron application and experimenting with using asar to package the node_modules and sources directories, while excluding other directories. However, I've run into an issue where when building the application with a ...

Obtaining the body from a post request in Node.js: A step-by-step guide

When sending data with the id using the post method to my node server, I encountered an issue where req.body is returning as undefined in my node file. This is what my index.html looks like: <html ng-app="IMDBApp"> <body> <div ng-contr ...

I am utilizing Python Django to display a message from a Python file in HTML. While the current code is functional, I would like the message to be showcased as a pop-up or alert notification

Using Python Django. The message is coming from a Python file and I would like to display it in HTML. The current code is functioning, but I would like the message to appear as a pop-up or alert. Register {% if messages %} {% for result in messages %} < ...

The CSS outline properties vary between input elements and input elements in focus

I'm encountering an issue with a box and its associated CSS outline style. When the box is focused, it should display a blue outline (which is working fine). However, upon form validation, if there is an error, the .error class is added which should c ...

I am looking to sort users based on their chosen names

I have a task where I need to filter users from a list based on the name selected from another field called Select Name. The data associated with the selected name should display only the users related to that data in a field called username. Currently, wh ...

Organize JSON data based on the timestamp

What is the most effective method for sorting them by timestamp using jquery or plain JavaScript? [{"userName":"sdfs","conversation":"jlkdsjflsf","timestamp":"2013-10-29T15:30:14.840Z"},{"userName":"sdfs","conversation":"\ndslfkjdslkfds","timestamp" ...

Utilizing Angular: Integrating the Http response output into a map

I have a situation where I am making multiple HTTP calls simultaneously from my Angular application. The goal is to store the responses of these calls in a Map. data: Map<number, any> = new map<number,any>(); --------------------------------- ...

Leverage the Google Maps JavaScript API v3 to retrieve details for multiple locations using the getDetails(request, callback

I successfully integrated the Google Maps JavaScript API v3 to create a personalized store locator for our company's website. While the current code is functional for two stores, it lacks scalability due to the unconventional methods used. My impleme ...

Issue with MUI Data Grid sorting: Data Grid sortComparator function returning undefined

I'm attempting to organize data with nested values in a data grid, but I keep receiving 'undefined' on the sortComparator of Data Grid Columns. Code: Column Data Setup: { headerName: 'Title', field: `${this.props.type} ...

Ways to troubleshoot setTimeout functioning during HTTP requests?

Utilizing Socket IO in my client app, I have implemented a feature to check for unread events. The process involves making a request to the backend, which then sets a 5-second timeout before checking for any new events and sending them back. // client soc ...

Is server-side validation of HTML form inputs using a lengthy sequence of if / else statements an effective approach?

Would it be practical to rely on a lengthy series of nested if/else statements in PHP for validating user input from an HTML form? For instance, when dealing with two fields, the approach might look like this: if (field one is correctly formatted) { ...