Webpack and TypeScript are throwing an error stating that `$styles` is not defined

I've encountered an issue with my typescript SharePoint spfx solution. After compiling using webpack, my $styles variable becomes undefined even though I am able to use the class names directly.

It seems like there might be a configuration problem at play here. Can anyone offer some assistance?

This is the SCSS code I'm working with:

@import "~bootstrap/scss/bootstrap";

.app {
   .top {
        text-align:center;
        justify-content: center;
        .customalert {
          margin-bottom: 0px !important;
          font-size: 14px;
        }
      }
  }

And here's the HTML output I'm trying to achieve:

import styles from './AppCustomizer.module.scss';
return `<div class="${styles.app}">
        <div class="${styles.top}">
          <div class="alert alert-${alertStatus} ${styles.customalert}">
            <strong>${alertTitle}</strong> ${alertDescription}
          </div>
        </div>
      </div>
    and here is my webpack.config.js:

        const path = require("path");
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');

    module.exports = {
      mode: "development",
      entry: ['@babel/polyfill',
        path.resolve(__dirname, './Classic/client/bootHeader.ts')],
      module: {
        rules: [
          {
            test: /\.tsx?$/,
            use: "ts-loader",
            exclude: /node_modules/
          },
          {
            test: /\.(s*)css$/,
            use: [
              // fallback to style-loader in development
              process.env.NODE_ENV !== "production"
                ? "style-loader"
                : MiniCssExtractPlugin.loader,
              "css-loader",
              "sass-loader"
            ]
          },
          {
            test: /\.(png|jp(e*)g|svg)$/,
            use: [
              {
                loader: "url-loader",
                options: {
                  limit: 15000, // Convert images < 8kb to base64 strings
                  name: "images/[hash]-[name].[ext]"
                }
              }
            ]
          }
        ]
      },
      plugins: [
        new MiniCssExtractPlugin({
          filename: "[name].css",
          chunkFilename: "[id].css"
        })
      ],
      resolve: {
        extensions: [".tsx", ".ts", ".js"]
      },
      output: {
        filename: "classicBundleAG.js",
        path: path.resolve(__dirname, "Classic"),
        libraryTarget: "umd"
      },
      //externals: [
      //  "@microsoft/sp-loader",
      //]
    };

One thing worth noting is that when I access the styles directly as "customalert", the style is recognized. However, $styles remains undefined if used in the code.

Answer №1

It seems like you are anticipating an object from the styles. This can only be achieved using css-modules. To enable this feature, simply add modules: true to your configuration in the css-loader:

          {
            test: /\.(s*)css$/,
            use: [
              // fallback to style-loader in development
              process.env.NODE_ENV !== "production"
                ? "style-loader"
                : MiniCssExtractPlugin.loader,
              {
               loader: "css-loader",
               options: {
                modules: true
               }
              },
              "sass-loader"
            ]
          },

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

connect a column from a separate array in pdfmake

In my current project, I am looking to link the values of an array that is different from the one present in the initial two columns. Is this achievable? (The number of partialPrice values aligns with the number of code entries). Despite several attempts ...

The mistake is indicating the npm title of a package that is not present

https://i.sstatic.net/5bywN.png An issue has arisen - the module cannot be found, even though such a module does not actually exist. The correct module name should be babel-plugin-proposal-class-properties (and the error is showing as 'babel-plugin-t ...

I need to compile a comprehensive inventory of all the publicly accessible attributes belonging to a Class/Interface

When working with TypeScript, one of the advantages is defining classes and their public properties. Is there a method to list all the public properties associated with a particular class? class Car { model: string; } let car:Car = new Car(); Object. ...

What is the best method to adjust the width of the PrimeNG ConfirmDialog widget from a logic perspective

Currently utilizing "primeng": "^11.2.0" and implementing the ConfirmDialog code below this.confirm.confirm({ header: 'Announcement', message: this.userCompany.announcement.promptMsg, acceptLabel: this.userCompany.announcement ...

Issue: Encountering an ObjectUnsubscribedError while using Observables in RxJS and Angular2

Currently, I am in the process of self-teaching Angular2 and realize that I need to find better resources. One issue I am facing is related to moving my data calls to a service and utilizing Reactive Subject & BehaviorSubject as recommended by a friend. Wh ...

Master the art of iterating through an Object in TypeScript

I need help with looping through an Object in TypeScript. While the following examples work in JavaScript, I understand why they pose a problem in TypeScript. Unfortunately, I am struggling to find the correct approach to solve this issue. Am I approaching ...

What is the reason for receiving an error with one loop style while the other does not encounter any issues?

Introduction: Utilizing TypeScript and node-pg (Postgres for Node), I am populating an array of promises and then executing them all using Promise.all(). While pushing queries into an array during iteration over a set of numbers, an error occurs when the ...

Issue with ToggleButtonGroup causing React MUI Collapse to malfunction

I'm having trouble implementing a MUI ToggleButtonGroup with Collapse in React. Initially, it displays correctly, but when I try to hide it by selecting the hide option, nothing happens. Does anyone have any suggestions on what might be causing this ...

The most suitable TypeScript type for a screen being utilized again in react-navigation v5

When it comes to typing screens under react-navigation v5, I usually follow a simple pattern: // Params definition type RouteParamsList = { Screen1: { paramA: number } Screen2: undefined } // Screen1 type Props = StackScreenProps<R ...

Loop through a collection of elements of a certain kind and selectively transfer only certain items to a different collection of a different kind

When working with typescript, I am faced with the challenge of dealing with two arrays: interface IFirst{ name: string; age: number } interface ISecond { nickName: string; lastName: string; } myFirstArray: IFirst[]; mySecondArray: ISe ...

Error receiving by React while updating an array with setState() in TypeScript

I am in search of a way to adjust a property of an item within an array by using the updater returned from setState. The function is passed down as props to the child, who then invokes it with their own index to update their status. const attemptToUpdate ...

Encountering CORS error when making a call to AWS API from Angular 9

Currently, I am working on implementing a post method in Angular 9 that interacts with an AWS API. However, upon calling the post function in Angular 9: this.http.post(url, body, requestOptions), I encountered an error in my browser stating: Access to XMLH ...

The attempt to combine an array of elements with another array using FieldValue.arrayUnion() in Firestore was unsuccessful

My cloud function is triggered when a specific event occurs. Within the function, I receive an array of strings like this example: let h:string[] = ["foo","bar","baz"]. When I attempt to update an array field within my document using names: admin.firestor ...

Creating a JSX.Element as a prop within a TypeScript interface

I need to create an interface for a component that will accept a JSX.Element as a prop. I have been using ReactNode for this purpose, but I am facing issues when trying to display the icon. How can I resolve this issue? export interface firstLevelMenuItem ...

The compilation of TypeScript extending DataType can sometimes result in errors

I have written a custom extension in my extensions/date.ts file which adds a method to the Date interface: interface Date { addDays: (days: number) => Date } Date.prototype.addDays = function(days: number): Date { if (!days) return this; let dat ...

Can Autocomplete in Angular4+ support multiple selection options?

I am trying to implement a multi-selection feature on filtered items using an autocomplete function. I found inspiration from this tutorial and attempted the following code: The component : <form class="example-form"> <mat-form-field class=" ...

Refresh Ionic 2 Platform

I'm currently working on an Ionic 2 app and whenever I make a change to the .ts code, I find myself having to go through a tedious process. This involves removing the platform, adding the Android platform again, and then running the app in Android or ...

Having trouble resolving all parameters for the SiteNotificationComponent: (?)

I encountered an issue while attempting to append a component to the DOM. The error message displayed was "Can't resolve all parameters for SiteNotificationComponent: (?).at syntaxError." My goal was to insert HTML content by invoking showNotificatio ...

Resolving Hot-Reload Problems in Angular Application Following Upgrade from Previous Version to 17

Since upgrading to Angular version 17, the hot-reload functionality has been causing some issues. Despite saving code changes, the updates are not being reflected in the application as expected, which is disrupting the development process. I am seeking ass ...

Issue: The module '@nx/nx-linux-x64-gnu' is not found and cannot be located

I'm encountering issues when trying to run the build of my Angular project with NX in GitHub Actions CI. The process fails and displays errors like: npm ERR! code 1 npm ERR! path /runner/_work/myapp/node_modules/nx npm ERR! command failed npm ERR! c ...