Can Webpack, with the help of plugins, compress my CSS files, relocate them to the dist folder, and automatically insert a tag into the index.html file?

My goal is to streamline my CSS files in my development environment by combining and minifying them into a single file. I want this new file to have a hashed name based on its content, which should automatically be linked in my index.html file within the distribution folder.

I believe this is achievable with Webpack 4, considering its versatility. Can someone guide me on how to set this up?

Importantly, I cannot use import statements or similar techniques in my JavaScript code for this task.

I've experimented with plugins like Mini Css Extract and Optimize CSS Assets within Webpack but haven't been successful in generating the desired output file yet (I understand that modifying the index.html won't happen, but having the CSS file is a good start).

The current structure of my files is as follows: 'mainFolder'/public/css <- source CSS folder, 'mainFolder'/dist/css <- target folder for minified file

My configuration currently looks like this:


    // JavaScript paths required for webpack 
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = { 
    entry: [
        './public/js/app.js',
        ...
        './public/js/lib/angular-semantic-ui.min.js'
    ],
    output: {
        filename: 'js/[contenthash].js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: 'dist'
    },
    devtool: 'source-map ',
    plugins: [
        new CleanWebpackPlugin(['dist'], {

        }), 
        new HtmlWebpackPlugin({
            title: 'Zenvite',
            template: './public/templates/index.html',
            filename: 'templates/index.html'
        }),
        new CopyWebpackPlugin([
            ...
        ]),
        new MiniCssExtractPlugin({
            filename: 'app.css',
            chunkFilename: '[contenthash].css',
        })
    ],
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                          publicPath: '../public'
                        }
                    },
                    "css-loader"
                ]
            }
        ]

    },
    optimization: {
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.css$/,
          chunks: 'all',
          enforce: true
        }
      }
    }
  },
};

I am still striving to achieve a merged and minified [contenthash].css file along with altering the index.html header section. Any assistance would be greatly appreciated, and feel free to ask if you need more information.

Answer №1

Ultimately, after the import statement was mistakenly removed during compilation, my supervisor approved its addition. We then proceeded to implement the following solution:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const TerserPlugin = require('terser-webpack-plugin');

module.exports = { 
    entry: [
        './public/js/app.js',
        './public/js/filters/weekday.js',
        './public/js/filters/dial-in.js',
        './public/js/filters/time.js',
        './public/js/filters/group-member.js',
        './public/js/filters/bool-to-icon.js',
        './public/js/filters/date-format.js',
        './public/js/filters/time-format.js',
        './public/js/services/main.js',
        './public/js/configs/config.js',
        './public/js/controllers/main.js',
        './public/js/pages/calendar/controller.js',
        './public/js/pages/company/view/controller.js',
        './public/js/pages/company/edit/controller.js',
        './public/js/pages/group-meeting/create/controller.js',
        './public/js/pages/group-meeting/detail/controller.js',
        './public/js/pages/group-meeting/view/controller.js',
        './public/js/pages/group-meeting-calendar/controller.js',
        './public/js/pages/login/controller.js',
        './public/js/pages/meeting-link/view/controller.js',
        './public/js/pages/meeting-link/edit/controller.js',
        './public/js/pages/meeting-link/detail/controller.js',
        './public/js/pages/user/view/controller.js',
        './public/js/pages/user/edit/controller.js',
        './public/js/lib/angular-semantic-ui.min.js'
    ],
    output: {
        filename: 'js/app.[contenthash].js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: 'dist'
    },
    devtool: 'source-map ',
    plugins: [
        new CleanWebpackPlugin(['dist'], {

        }), 
        new HtmlWebpackPlugin({
            title: 'Zenvite',
            template: './public/templates/index.html',
            filename: 'templates/index.html'
        }),
        new CopyWebpackPlugin([
            //{ from: 'public/css', to:'css'},
            { from: 'public/media', to:'media'},
            { from: 'public/js/pages', to: 'js/pages', ignore: [ '*.js' ]},
            { from: 'public/templates/app.html', to: 'templates'}
        ]),
        new MiniCssExtractPlugin({
            filename: 'css/app.[contenthash].css'
        })
    ],
    module: {
        rules: [{
            test: /\.(sa|sc|c)ss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                ],
        }]
    },
    optimization: {
        minimizer: [
            new TerserPlugin({
                cache: true,
                parallel: true,
                sourceMap: true, // Must be set to true if using source-maps in production
        }),

            new OptimizeCSSAssetsPlugin({})
        ]
   }
};

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

Flow bar for micro-tasks

In my current project, I am faced with the task of organizing a series of 4 mini tasks and displaying to the end user which specific mini task they are currently on. To accomplish this, I have been utilizing image tags for each task. <img>1</img ...

Issue with Bootstrap 5 Card Header not extending to full width

I have implemented tables within cards using a CDN. While the table looks fine in wide widths, it does not resize to fill the entire width when squeezed. Below is the HTML code: <div class="card table-responsive"> <div clas ...

Mastering Bootstrap: Achieving flawless column stacking in succession

I am currently integrating bootstrap into my existing HTML code, but I only require it in two specific sections to avoid rewriting the entire code. Everything looks fine on my 1080p screen as intended. However, when I resize the screen slightly The titl ...

Place objects at the bottom of the screen

I'm currently using Bootstrap 4 and facing an issue where I want to keep a row with some columns at the bottom of the page. However, when I add position fixed and set it to bottom, the placement gets disrupted and does not stay centered. I suspect thi ...

I attempted to utilize the <map> tag in creating a circular image that functions as a hyperlink, but unfortunately, it is not functioning correctly

I've been trying to create a round button using the code below, but something seems to be wrong with it. The issue I'm facing is that the area around the image is also clickable, even though I have used border-radius. Can someone please take a lo ...

Tips for showcasing boxed numerical characters on a website

Currently, I am tackling a project that involves converting a PDF into HTML. The original .ai file shows some numeric characters inside a box: https://i.sstatic.net/dAMU2.png Even though I am aware that the font used in the file is GothicMB101Pro DeBold- ...

Intel XDK problem with HTML5/CSS3 footers overlapping headers in my project

I am in the process of developing an application using drag and drop features from the Intel XDK/App Designer. The main concept behind this app is to provide users with basic tutorials and incorporate geolocation services. My approach involved following th ...

I am having trouble getting my HTML to properly link with my CSS while using Chrome OS

My website code is not linking with the CSS file <!DOCTYPE html> <html> <head> <link href="main.css" rel="slylesheet" text="text/css"> <title></title> </head> <body> < ...

Is it possible to create rounded or curved top corners for a box using HTML?

I'm looking to create a card with rounded top corners and wondering if there is a way to achieve this. Currently, here is the code I have: <div id="card1"> <div id="card1i"></div> </div& ...

Implementing a JQuery script that triggers every time there is a change in the scroll

This script creates a shrinking effect on a box followed by a fade-in/out transition when the scroll position changes. However, the issue is that it triggers every time there is a scroll position change. For example, if the scroll position is at 100px and ...

What is the best method to style a child input element's placeholder using Tailwind CSS?

I'm currently working on a project and trying to translate a CSS style that targets the ::placeholder pseudo-element into Tailwind CSS. However, I have encountered some challenges during this process as I'm not entirely sure of the correct approa ...

Arranging card images in a row using semantic cards for optimal alignment

Trying to create a row of semantic-ui cards with images at the top, I ran into an issue with varying image heights causing different card title positions. The goal is to have all images be the same height while still adapting to larger screens. Although I ...

Issues with requiring MongoDB in Vue-cli webpack-simple

Currently, I am facing an issue while setting up a new project using vue-cli with the webpack-simple template. Everything runs smoothly until I attempt to integrate mongodb. Upon adding the line import mongodb from 'mongodb' I encounter the fo ...

Is it possible to override Bootstrap or not?

It's quite a puzzle to figure out when I can and cannot override Bootstrap classes or IDs with custom CSS. For instance, it seems easy enough to change the default navbar-dark background and font style, but altering the font color and size proves to ...

Ensuring the alignment of a personalized list bullet with the accompanying text

Looking to make the bullet point next to an li element larger? The common approach is to eliminate the standard point, add a custom one using the :before selector, and adjust the font size of the added point. While this technique somewhat achieves the goa ...

Tips on how to efficiently wrap content within a column layout, and to seamlessly shrink it if necessary

I recently encountered an issue where I am attempting to create a three-column layout with each column filled with a dynamic number of divs (boxes) ranging from 5 to 15, each with its own height based on its content. These divs are expected to: 1) Be dis ...

Issue with HTML and CSS Grid alignment coupled with CSS syntax error on RBRACE

I'm in the process of updating my website indexes and decided to incorporate grids. However, when attempting to implement grids using Dreamweaver, I encountered several issues. Firstly, an error message appeared stating "Expected RBRACE at line 72, co ...

How come my webpage is not loading properly with CSS applied?

My website can be found at: www.rootscope.in While working on the CSS for my site, I encountered an issue with the following code: .loader { position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: 9999; backgroun ...

Is it unwise to conceal the horizontal scrollbar?

My webpage includes a jquery slideshow using the jquery circle plugin, featuring the "shuffle" option. var slideshow = $('#slider').cycle({ fx: 'shuffle', shuffle: { top: 0, left: 1300}, .... When the images move out ...

What is causing this array to automatically alter its value?

How can I prevent A from changing its value when I only want to modify Q in the first loop of this html/javascript code? Why does A change even though I am only changing Q? What steps can I take to avoid A from changing? <!DOCTYPE html> <html& ...