Tips for preventing duplicate imports in Sass with the @use rule in Webpack

My sass modules have the ability to import each other as shown in the examples below:

// LinearLayout.scss
@mixin LinearLayout { ... }
linear-layout { @include LinearLayout; }

// ScrollView.scss
@use "LinearLayout" as *;
@mixin ScrollView {
    @include LinearLayout;
    ...
}
scroll-view { @include ScrollView; }

As a result, every sass module is included in the bundled css file through imports in scripts, leading to duplicate css selectors in the final output.

Is there a way for me to eliminate these duplicates?

Answer №1

Key requirement for both Webpack versions

It appears that both plugins operate within a specific webpack bundling lifecycle dictated by the presence of the mini-css-extract-plugin. This means you cannot utilize style-loader; instead, consider using html-webpack-plugin.

The following snippet demonstrates how your webpack.config.ts file should look like. Remember to set optimization.minimize to true for it to function even during development.

import type Webpack from "webpack";
import HtmlBundler from "html-webpack-plugin";
import CssExtractor from "mini-css-extract-plugin";

// For webpack@5
import CssMinimizer from "css-minimizer-webpack-plugin";
// For webpack versions under 5
import CssMinimizer from "optimize-css-assets-webpack-plugin";

const config: Webpack.Configuration = {
    ...
    plugins: [
        new HtmlBundler({
            template: "yourHtmlTemplate.html"
        });
        new CssExtractor({
            filename: "outputCssFilename.css",
        }),
    ],
    module: {
        rules: [
            {
                test: /\.s[ac]ss$/,
                use: [
                    CssExtractor.loader,
                    "css-loader",
                    "resolve-url-loader",
                    "sass-loader",
                ]
            },
        ],
    },
    optimization: {
        minimize: true, // set true to run minimizers also in development
        minimizer: [
            new CssMinimizer(),
        ],
    },
};

export default config;

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

Tips for implementing react-select types in custom component development

Currently, I'm in the process of developing custom components for DropdownIndicator to be used on react-select with Typescript. However, I am encountering difficulties with the component's type due to my limited experience with Typescript. I wou ...

Issue with Angular 5 Application - "Implementations cannot be declared in ambient contexts"

Recently in my Angular 5 project, I started encountering an issue with the observable object. Everything was working smoothly until about a week ago when I began receiving this error message: ERROR in node_modules/rxjs/Observable.d.ts(20,31): error TS1183 ...

Using Bootstrap 4 with Angular 2: A Beginner's Guide

Currently, I am in the process of developing an Angular 2 application using TypeScript. My goal is to integrate the Bootstrap 4 framework with some custom theming. Is this achievable? I have encountered issues with the "ng2-bootstrap" npm package, as it d ...

Strategies for preventing multi-level inheritance of TypeScript class properties and methods

In my current JavaScript class structure, the DataService is defined as follows: // data.service.ts export class DataService { public url = environment.url; constructor( private uri: string, private httpClient: HttpClient, ) { } ...

Angular is unable to bind with 'dragula' because it does not recognize it as a valid property of 'ul'

I've been attempting to incorporate dragula into my Angular 2 application, but I'm struggling to get it functioning. This is what I have added in my app.module.ts file: import { DragulaModule, DragulaService } from 'ng2-dragula/ng2-dragula ...

How can I utilize Pinia and TypeScript to set the State using an Action?

I have a Pinia + TypeScript store named user.ts with the following structure: import { User } from 'firebase/auth'; import { defineStore } from 'pinia'; export const useUserStore = defineStore('user', { state: () => ( ...

Utilizing global enumerations within VueJS

Is there a way to effectively utilize global enums in Vue or declare them differently? My current setup is as follows: Within my types/auth.d.ts: export {}; declare global { enum MyEnum { some = "some", body = "body", o ...

Using Typescript: A guide on including imported images in the output directory

typings/index.d.ts declare module "*.svg"; declare module "*.png"; declare module "*.jpg"; tsconfig.json { "compilerOptions": { "module": "commonjs", "target": "es5", "declaration": true, "outDir": "./dist" }, ...

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

Unable to load HomeComponent in Angular 4 due to an error

Currently working on creating an app using the "An API of Ice and Fire". Encountering an issue with a displayed error message "ERROR Error: "[object Object]"" when attempting to redirect to homeComponent. Attached are screenshots displaying the error: B ...

The element selector for the <code> tag is not recognized in SCSS

Update on 2020/02/23: I have made some additions to my project. Apologies for the lack of information provided earlier. The project I am working on is a modified version of the [Gatsby + Netlify CMS Starter][1]. In the process, I swapped out all.sass wit ...

Utilizing the WebSocket readyState to showcase the connection status on the application header

I am currently in the process of developing a chat widget with svelte. I aim to indicate whether the websocket is connected or not by utilizing the websocket.readyState property, which has the following values: 0- Connecting, 1- Open, 2- Closing, 3- Close ...

Implementing Firebase as an Authentication Middle Layer for Express.js

I am currently working on developing an authentication middleware to verify the presence of a valid firebase token in the request header. Here's the code snippet: auth.ts import * as firebase from 'firebase-admin'; import { NextFunction, Re ...

What is the best method to condense an array or extract only the valid values?

Looking to find the total count of properties that are true from an array of objects? Here's an example: let data = [ { comment: true, attachment: true, actionPlan: true }, { whenValue: '', ...

Ways to display all utilized typescript types within a project

Here is a snippet of code I'm working with in my project: describe('Feature active', () => { it('Should render a Feature', () => { const wrapper = shallow(<MyComponent prop1={1}/>); expect(wrapper.prop('p ...

After updating the state in a Reducer with Redux Toolkit, make sure to utilize a

Issue: Seeking efficient code writing methods. Here is a detailed example of my Redux Toolkit slice below: import { createSlice } from '@reduxjs/toolkit'; import { setCookie } from '../../utils/storageHandler'; const initialState = { ...

Assign custom keys to request object parameters before reaching the controller in the map

I have a Loopback 4 application where the request object's property keys are in snake_case and they correspond to our database column names which are in StudlyCase. What I want is to change the application property names to camelCase. This means that ...

The number of keys in the related object must correspond to the length of the array in Advanced Generic Types

Can we achieve type safety across rows and columns by having one object define the structure of another? Starting Point: export interface TableColumn { name: string; type: "string" | "number" | "action"; id: string; } ...

Upon successfully maneuvering vendors who fail to load the NEXT.JS Link

Here is an image that is not displaying properly. The navbar's responsiveness seems to be causing the issue. return ( <Link key={index} href={'/'+item.id} > <li className="nav-item dropdown position-stati ...

The incorrect starting points for nested for loops

I'm facing an issue while utilizing a nested for loop to generate x and y coordinates for a method call. Strangely, the loop variables seem to be starting off at incorrect values when I check using console.log. What could be the reason behind this une ...