Tips for compressing css styles with webpack version 3

My goal is to optimize and minify my CSS for production, but I'm encountering errors with my current implementation. Here's a snippet of my webpack 3 configuration in config.production.js:

var webpack = require("webpack");
var path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");


module.exports = {
    entry: [
        "./src/index.tsx","./src/assets/css/styles.css"
    ],

    output: {
        filename: "bundle.js",
        publicPath: "/",
        path: path.resolve(__dirname, "dist")
    },

    // Enable sourcemaps for debugging webpack's output.
    // devtool: "cheap-module-source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },

    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }
        }),
        new ExtractTextPlugin("styles.css"),
    ],

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, use: ["awesome-typescript-loader"] },
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { test: /\.js$/, enforce: "pre", use: "source-map-loader" },
            { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }
        ],
        loaders: [ {
            test: /\.js|.jsx?$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader',
        }, {
            test: /\.(jpe?g|png|gif|svg)$/i,
            loaders: [
                'file?hash=sha512&digest=hex&name=[hash].[ext]',
                'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
            ]
        } ]
    }
};

ERROR in multi ./src/index.tsx ./src/assets/css/styles.css Module not found: Error: Can't resolve 'style-loader' in 'C:\Users\iluli\Documents\socfinder_search\frontend' @ multi ./src/index.tsx ./src/assets/css/styles.css npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! [email protected] build:

webpack --config webpack.prod.config.js -p
npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the [email protected] build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I noticed that my CSS file is not being generated into the build folder.

UPDATE: After installing css-loader, the styles.css file is now generated into the build folder, but it remains unminified. I would like the production version to have a minified CSS, where all styles are combined into one line.

Answer №1

Consider incorporating the "minimize" feature into the css-loader:

{ test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader", options: { minimize: true} }) }

Source: here

Answer №2

Make sure to include the style-loader in your list of dependencies:

npm install style-loader --save-dev 

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

Is there a way to retrieve the response body in Express framework?

In my NodeJS API using Express, I am attempting to save the response body of a request. To achieve this, I have created two middleware functions. app.use((req, res,next) => { res.status(404).json({ errors: [{ field: "url", ...

Filtering data in Asp.net MVC 3 and converting it to JSON format

For my asp.net mvc 3 project, I'm considering the best approach for handling data: should I pass all the data via JSON and filter it with JavaScript, or should I filter the data first and then convert it to JSON? If filtering the data before passing ...

Trouble arises when trying to insert a script tag into a live code editor using HTML

A few days ago, I successfully created a live code editor using the ace 1.2.9 library for my website guides. Now, I'm attempting to create a basic example, but when I try to enter text in the designated text area for the guides, the studio code compil ...

The stickme package (NodeJS, NPM) does not have any versions currently accessible

Recently, the stickme plugin in my office project was working flawlessly. However, as of last week, it has started failing when I try to build the project. Even attempting to manually install the stickme plugin with npm install stickme results in the foll ...

Manage a frame directly from the parent page

I am faced with a situation where I have a web page with two textboxes and a button. Unfortunately, I am unable to alter the contents of this page in any way. My goal is to find a way to automatically populate the first textbox with some text when the pag ...

The styling of the React component is not being applied as expected by the .Css file

My title component seems to be having trouble applying the CSS styles as expected. I'd like it to have a green background, but for some reason, it's displaying as white. Below is the Component Js file: import React from "react"; funct ...

`Navigating through database structures using node js`

When it comes to interpreting a Database {} object in JavaScript, I am currently working on back end scripts for validating a registration form. Specifically, I need to make sure that the username and email being used for registration are not already taken ...

Block Button styles not displaying in IE when set to Full Width

I can't figure out why, but it seems to be functioning properly on every other internet platform except this one. The first picture shows the button in IE, the second contains the code, and the third displays the button in Chrome. https://i.sstatic. ...

Utilizing Node.js and Express: A guide to accessing remote APIs within the server.get() method

Encountering CORS issues, I am seeking a solution to execute an external REST API call from within my node express server. Unfortunately, the following code snippet does not work as expected. How can I modify this code to successfully retrieve and return ...

Unable to display toast notification in React/MUI/Typescript project

Currently tackling error notifications targeted at 400,401, and 500 errors within a large-scale project. I am facing an issue where I want to integrate my ErrorToastNotification component into my layout.tsx file to avoid duplicating it across multiple page ...

Tips for effectively incorporating customized validation into an array using vuelidate

My array of objects has a specific structure that looks like this varientSections: [ { type: "", values: [ { varientId: 0, individualValue: "" } ] } ] To ensure uniqueness, I implemented a c ...

How can I identify the main text of a specific <MenuItem/> component in ReactJS Material-UI?

I've been working with the Material-UI Dropdown Menu component and I'm trying to figure out how to console log the primaryText of the selected <MenuItem/>. Can anyone provide guidance on how to achieve this? ...

Is there a way to halt or end an interval within a function triggered by useEffect()?

I am currently working on a countdown timer script using react.js. The timer displays a 3 or 5 seconds countdown before starting, with data for these countdowns coming from another component. I am facing an issue with controlling the main countdown timer ...

Configuring HaProxy to Load Balance Node.js for WebSockets

Recently, I set up HaProxy 1.6 on my Debian system with the intention of distributing WebSocket (WS://) connections among multiple server instances. The servers running the WebSocket service share the same IP Address but have different ports: 192.168.10.1 ...

What is the best way to introduce a time delay between two JavaScript functions?

Here is some JavaScript code that I am working with: clientData.reloadTable( "CreateCSV", "/create/file" ); $("#downloadFrame").attr("src","/download/download"); The first statement in the code above creates a CSV file on the disk. The second statement d ...

What is the best way to create a test for a program that relies on standard output?

I am currently focusing on enhancing test coverage for this particular file. 'use strict' /** * Retrieves the logging configurations in use * * @param {String} name Name of the logger. Should correspond ...

Tips for resolving the error "Binding element has no default value and initializer provides no value in TypeScript"

I am currently in the process of converting a JavaScript Apollo GraphQL API project to TypeScript. During this migration, I encountered an error related to a user code block: var idArg: any Initializer provides no value for this binding element and the ...

Exploring the integration of mixins from .scss files within node_modules into our .tsx or .jsx files for enhanced styling

I am currently facing a challenge with importing a .scss file from one of the installed node_modules into my .tsx file. The scss file contains a mixin named @mixin make-embedded-control($className: embedded-control){.....} which has all the necessary css ...

The unique GopikaTwo Gujarati font is unfortunately not compatible with Android mobile browsers and hybrid applications

I am currently trying to incorporate the custom font GopikaTwo into my hybrid application. Below is the code snippet I have added to my CSS file: @font-face { font-family: 'GopikaTwo' !important; src: url('GopikaTwo.eot') !impo ...

locating the truth value of the data in an array retrieved from MongoDB

When returning from the mongoose find() function, I need to ensure that is_reqestor = true is checked. However, when updating the document, I pass the id which needs to be updated. let filter = { is_reqestor: true } if (!is ...