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

Dissimilarities in behavior between Angular 2 AOT errors

While working on my angular 2 project with angular-cli, I am facing an issue. Locally, when I build it for production using ng build --prod --aot, there are no problems. However, when the project is built on the server, I encounter the following errors: . ...

Struggling to retrieve posted data using Angular with asp.net

I have encountered an issue while sending a post request from Angular to my ASP.NET server. I am trying to access the values of my custom model class (SchoolModel) and I can see that all the values are correct inside Angular. However, when I attempt to ret ...

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

Tips for including an authorization token in an HTTP request

I encountered a 401 unauthorized error when trying to access my REST endpoint, likely due to the security measures I have implemented. I suspect that there might be an issue with how I am handling the HTTP headers. The application utilizes a Spring Boot b ...

Attribute specified does not belong to type 'DetailedHTMLProps<ButtonHTMLAttributes

I am working on creating a reusable 'button' component and I would like to include a href attribute so that when the button is clicked, it navigates to another page. An Issue Occurred: The following error was encountered: 'The type '{ ...

Enforcement of Class Initialization in Typescript 2.7

After initializing a sample project using the Angular template in Visual Studio 2017, I made sure to update the package.json file with the latest module versions. However, upon executing the npm install command and navigating to the site, an error related ...

What is the procedure for linking the value (<p>John</p>) to the mat form field input so that it displays as "John"?

Can I apply innerHTML to the value received from the backend and connect it to the matInput? Is this a viable option? ...

Tips for properly implementing an enum in TypeScript when using the React useState hook

What's the correct way to utilize my useState hook? I have this enum type: export enum Status { PENDING = 'pending', SUCCESS = 'success', ERROR = 'error', } And the useState hook: const [isValid, setIsValid] = use ...

I am unable to utilize the Web Share API for sharing a file within my React app written in TypeScript

Trying to launch a WebApp for sharing files has been quite a challenge. After some thorough research, I stumbled upon the Web Share API which seemed like the perfect solution based on standard practices. The documentation provided a clear outline of how it ...

Is it possible to write TypeScript and execute it directly with Node?

I am attempting to write some basic typescripts but I am encountering an issue with the setup below: node src/getExchangeAndTickerList.ts import * as mkdirp from 'mkdirp'; ^^^^^^ SyntaxError: Cannot use import statement outside a module ...

While using axios to make a GET request, I encountered errors when checking for .isSuccess in react

const searchInvoiceList = async ( plantLocation: string, invoiceType: string ) => { let dataList: InvoiceData[] = []; await axios .get(`${linkURL}inv/getControlList/${plantLocation}/${invoiceType}`) .then((response) => { dataLis ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Examining the array to ensure the object exists before making any updates in the redux

Is there a way to determine if an object exists in an array and update it accordingly? I attempted to use the find method, but it couldn't locate the specified object. I also tried includes, but it seems to be unable to recognize the item within the ...

Bundle Angular library exports along with its corresponding models

I am in the process of developing an angular library for our company's private npm repository. Within this library, I aim to export classes that are utilized (injected via @Input()) in the library components. Here is a sample model: export class AdsT ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Is it possible to limit the items in a TypeScript array to only accept shared IDs with items in another array?

I'm creating an object called ColumnAndColumnSettings with an index signature. The goal is to limit the values of columnSettings so that they only allow objects with IDs that are found in columns. type Column = { colId: string, width?: number, s ...

I am experiencing issues with the rendering of my q-btn elements in Quasar and they are

I recently started using Quasar and encountered an issue with my q-btn component buttons displaying white backgrounds at random, despite having added a background-color in the external stylesheets. Here are some examples of this perplexing problem: The e ...

Setting key-value pairs in TypeScript objects explained

I encountered an issue with setting key/value pairs on a plain object. type getAObjectFn = <K extends string, V>(k: K, v: V) => Record<K, V> const getAObject: getAObjectFn = (k, v) => { return { [k]: v } } console.log(getAObject ...

Closing Accordions Automatically

Hello everyone! I'm currently working on a NextJS project and facing an issue with my dynamic accordion component. I'm using typescript, and the problem lies in only one accordion being able to open at a time. How can I ensure that only the spec ...

Binding iframes in Angular 6

Is there a way to display iframe code stored in a variable within a div? Here's the HTML code: <div class="top-image" [innerHTML]="yt"></div> And here's the TypeScript code: yt = '<iframe class="w-100" src="https://www.you ...