Merging SCSS and CSS into a unified file using WebPack

Trying to grasp webpack as a beginner is proving to be quite challenging for me. I'm struggling with the concept of merging multiple scss and css files together using webpack, after transpiling the sass.

Unlike gulp, where I could easily transpile sass to css and then concatenate them in separate steps, webpack seems to handle everything simultaneously.

This basic requirement surely has a straightforward solution for those who are more experienced in webpack.

I have managed to successfully output transpiled scss to css and separately output a css file from css input. However, I am stuck on how to combine them using webpack.

Shown below is my webpack.config.js file:

const path = require('path');
const webpack = require('webpack');

var ExtractTextPlugin = require('extract-text-webpack-plugin');

const extractCSS = new ExtractTextPlugin('extractedCSS.css');

const extractSass = new ExtractTextPlugin({
    filename: "extractedSASS.css",
    disable: process.env.NODE_ENV === "development"
});

module.exports = function (env) {
    return {
        context: path.resolve(__dirname, './wwwroot/app'),
        entry: {
            main: './index.js',
            vendor: 'moment'
        },
        output: {
            filename: '[name].[chunkhash].js',
            path: path.resolve(__dirname, './wwwroot/mytempdist')
        },
        module: {
            rules: [{
                test: /\.css$/,
                use: extractCSS.extract({
                    use: 'css-loader'
                })
            },
            {
                test: /\.scss$/,
                use: extractSass.extract({
                    use: [{
                        loader: "css-loader"
                    }, {
                        loader: "sass-loader"
                    }],
                    fallback: "style-loader"
                })
            }
            ]
        },
        plugins: [
            new webpack.optimize.CommonsChunkPlugin({
                name: 'vendor',
                minChunks: function (module) {
                    return module.context && module.context.indexOf('node_modules') !== -1;
                }
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: 'manifest' 
            }),
            
            extractSass,
            extractCSS
        ],
        devtool: 'inline-source-map'
    }
}

Now, how do I tweak the above configuration to merge both sass and css into a single output file?

Just in case it's relevant, here is an excerpt from my index.js file (entry point). toastr is an npm package, and pace is simply a downloaded css file:

var toastr = require('toastr');
import 'toastr/toastr.scss';

import pace from './../lib/pace/pace.min.js';
import './../lib/pace/pace.css';

Answer №1

You currently have 2 separate instances of ExtractTextPlugin set up with explicit names for loading css and scss files.

However, it would be more efficient to only use 1 instance of the plugin to combine all CSS files and utilize a single rule for both scss and css files.

{
    test: /\.s?css$/,
    use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: ['css-loader', 'sass-loader']
    })
}

This setup will handle both scss and css files and output them into a single consolidated CSS file.

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

Ways to keep the position of an expanded collapsible table from Material UI intact

I found a collapsible table code snippet on this website: https://mui.com/material-ui/react-table/#collapsible-table However, there seems to be an issue where when I expand a row, the table "grows up" as it increases in size. This behavior is not ideal. I ...

retrieving the value of a field within an array

Here is my code snippet: <div class="label">{{ item.data[0] }}</div> and in the view, this is what I have: { "id": 6, "firtname": "JHON ", "lastname": "SCALA", "fullname& ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

The Angular framework's structure is loaded in a combination of synchronous and asynchronous ways once the primeng tableModule

Encountered this error while trying to load the TableModule from primeng into my components module file and running 'npm run packagr': Maximum call stack size exceeded To address this, I switched my primeng version from primeng12 to primeng11.4. ...

Increase the visibility of a div using Jquery and decrease its visibility with the "

Can anyone assist me with implementing a "show more" and "show less" feature for a specific div? I have put together a DEMO on codepen.io In the DEMO, there are 8 red-framed div elements. I am looking to display a "show more" link if the total number of ...

having difficulty applying a border to the popup modal

Currently, I am utilizing a Popup modal component provided by the reactjs-popup library. export default () => ( <Popup trigger={<button className="button"> Guide </button>} modal nested > {(close: any) =&g ...

Is there a way to hide a button on this virtual keyboard after it has been clicked?

After creating a virtual keyboard using HTML and CSS, I am looking to implement JavaScript code that will hide a button after it is clicked. Here is the code I have tried so far: function hideButton() { var button = document.getElementById("simple_butto ...

`Encountering an unknown index while using AJAX to retrieve data from a PHP file

When using AJax to call a PHP file and retrieve values, I encountered an issue where the called PHP file returns an unidentified variable upon submission. Here is the script being used: <script> function showPrice(str) { if (str == "") { ...

Achieving optimal hardware performance for WebGL compatibility is essential

Lately, I have been exploring the world of Three.js to create impressive 3D scenes in WebGL. To ensure compatibility for all users, I have also developed versions using Three's CanvasRenderer which may not be as detailed but can still function on brow ...

Utilizing JSON Data with Angular

Currently, I am in the process of developing an AngularJS client that communicates with a REST API running on NodeJS. To retrieve data, I make GET requests by accessing specific URLs with stock symbols appended, such as localhost:8080/stocks/aapl for Apple ...

A gojs swim lane diagram requires a date axis to provide accurate time representation

I am currently working on a web application that requires a vertical swim lane activity diagram with a customized date axis displayed alongside it. The nodes in the diagram should be positioned based on their date attribute, and users should have the abili ...

Determining data using the AngularJS Slider component

I am currently utilizing the angularJS slider from this source: https://github.com/venturocket/angular-slider The sliders are functioning correctly, but now I need to extract the values from them for basic calculations. The HTML code snippet is as follo ...

Troubleshooting an Error in the Node Package Manager Test Case

I encountered an error while executing the npm command in the "c:\project" directory nyc --reporter=lcov mocha internal/modules/cjs/loader.js:985 throw err; ^ Error: Cannot find module 'C:\project\node' at Function.Module ...

Pause jQuery at the conclusion and head back to the beginning

As a beginner in the world of jQuery, I am eager to create a slider for my website. My goal is to design a slideshow that can loop infinitely with simplicity. Should I manually count the number of <li> elements or images, calculate their width, and ...

Guide to setting up a datePicker in a cellEditorSelector

In my grid, I want to have different editors for different rows within the same column. The ag-Grid documentation provides information on how to achieve this using colDef.cellEditorSelector as a function: link I have successfully created unique editors fo ...

Tips for getting the setInterval function to work with a progress bar even when a tab is not in focus

After browsing through similar questions, I couldn't find the answer I was looking for. As a newbie in programming experimenting with JavaScript Progress Bar, I encountered an issue where the progress bar would pause and the counter wouldn't coun ...

Running a cfquery in a cfc and passing parameters through AJAX

I am currently setting up a system to retrieve data from my ColdFusion database using JavaScript. However, I am encountering an error and unsure of its cause since I am relatively new to CF. The specific engine I am utilizing is ColdFusion MX 7. Below is ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

Discover the Google Chrome Extension that allows you to easily obtain JSON data from your

Here is the structure I have: And below is my manifest.json: { "manifest_version": 2, "name": "Doktor-MD", "description": "Share links on Doktor-MD through the browser.", "version": "1.0", "permissions": [ "http://www.google.com/" ], "browser_action": ...

Creative jQuery hover effects tailored to the size of the viewport

Currently expanding my knowledge of jQuery and encountering an issue with some code. I am trying to incorporate an animation effect (fadeIn/fadeOut) when the user hovers over a specific element. However, if the viewport is resized to below 480px for mobil ...