Bringing in SCSS using Typescript, React, and Webpack

I am trying to utilize .scss classes by importing them and applying them to the className property of a React component.

Here is the structure of my project :

root/
  ...
  config/
    ...
    webpack.config.js
  src/
    ...
    global.d.ts
    app/
      ...
      components/
        layout/
          ...
          Box/
            Box.scss
            Box.tsx

The contents of the .d.ts file are as follows :

declare module '*.scss' {
  const content: { [className: string]: string }
  export = content
}

For the webpack configuration in webpack.config.js, I have included the following rules:

...
module: {
    rules: [
      // assets (.css, .scss)
      {
        test: /\.s?css$/i,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
      // typescript
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: path.resolve(rootPath, 'node_modules'),
      },
    ],
  },
...

Inside Box.scss, I have defined the styling for the .Box class. Here is the code snippet:

.Box {
  padding: 16px;
  border-radius: 4px;
  text-align: center;
  color: #ede9f9;
  font-weight: 700;
  background-color: #47b0b0;
  box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.25);
}

In the Box.tsx file, I import the styles from Box.scss and attempt to apply them to the Box component. However, when I try to access styles.Box, it returns undefined. What could be causing this issue?

Answer №1

Just wanted to share that I've never come across the idea of directly importing scss into a project.

It seems like scss is primarily used for simplifying the styling process before compiling it into regular css.

Personally, I work with both style.scss and style.css files.

When using npm, I execute "sass --watch style.scss style.css" to automatically compile style.scss into style.css whenever there are changes.

Afterwards, I import style.css as usual in my React application.

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

Best Practices for Managing Message Alerts in React with Material-UI

I'm currently working on a web application with React and Material UI, which includes a registration form. After submitting the registration form successfully, I want to display a success message at the top of the page. To ensure consistency across m ...

Is it possible to execute a REST call in JavaScript without utilizing JSON?

(I must confess, this question may show my lack of knowledge) I have a basic webpage that consists of a button and a label. My goal is to trigger a REST call to a different domain when the button is clicked (cross-domain, I am aware) and then display the ...

Error encountered when attempting to listen on port 443: EADDRINUSE

My React application requires an HTTPS connection, so I have to run it on port 443. Regardless of the port I use, I keep encountering the following error: 0|server | at Module.load (node:internal/modules/cjs/loader:981:32) 0|server | at Functi ...

What is the best way to make a scrollable `div` that is the same height as my `iframe` with Material-UI?

I am developing a responsive Video Player with an accompanying playlist designed for Desktop and larger screens. The playlist has the potential to contain a large number of items, possibly in the hundreds. To view my progress so far, please visit https:// ...

Varying heights based on the screen size

Currently, I am in the process of designing my website and incorporating some wave elements to enhance the background. However, I've encountered some issues when resizing the screen. Specifically, the waves seem to shift with a space between them as t ...

Display a helpful tooltip when hovering over elements with the use of d3-tip.js

Is it possible to display a tooltip when hovering over existing SVG elements? In this example, the elements are created during data binding. However, in my case, the circles already exist in the DOM and I need to select them right after selectedElms.enter ...

What's preventing my Angular list from appearing?

I am currently developing an Angular project that integrates Web API and entity framework code first. One of the views in my project features a table at the bottom, which is supposed to load data from the database upon view loading. After setting breakpoin ...

Proper method for determining return type through the use of `infer`

I need to find out the return type based on input values, like in the code below: type ReturnType<S> = { array: S extends 'number' ? number[] : S extends 'string' ? string[] : never; value: S extends 'number' ? n ...

access the ckeditor within the frame

I have a CKEditor in a frame and am experiencing an issue. When I try to console log from the browser, it won't work until I inspect near the frame and perform the console log again. [This is the CKEditor] https://i.stack.imgur.com/fWGzj.png The q ...

The Next JS router is failing to return the variable page ID

In my Next.js application, I have implemented a requireAuth component to protect the logged in pages: import useAuth from '../../hooks/useAuth'; import { useRouter } from 'next/router'; import { useEffect } from 'react'; cons ...

A TypeScript object with user-defined keys

I have a question about utilizing TypeScript records with a custom Type as keys. Essentially, I have a specific type (a limited set of strings) that I want to use as keys for my record. My goal is to start with an empty initialization of this record. type ...

Contrasting outcomes when tackling a problem in node.js versus python

After tackling a challenging leetCode problem, I successfully came up with the following solution: Given d dice, each with f faces numbered from 1 to f, determine the number of possible ways (modulo 10^9 + 7) to roll the dice so the sum of the face up nu ...

Determine characteristics of object given to class constructor (typescript)

My current scenario involves the following code: abstract class A { obj; constructor(obj:{[index:string]:number}) { this.obj = obj; } } class B extends A { constructor() { super({i:0}) } method() { //I wan ...

What sets apart jQuery's `click`, `bind`, `live`, `delegate`, `trigger`, and `on` functions, and how can they be utilized differently in coding

I have gone through the documentation for each function provided on the official jQuery website, but I couldn't find any comparison listings for the following functions: $().click(fn) $().bind('click',fn) $().live('click',fn) $().d ...

Having trouble with SCSS styles not being applied after refactoring to SCSS modules?

Currently, I am in the process of restructuring an application to ensure that component styles are separated from global styles using CSS modules. However, I have come across an issue where the styles are not being applied correctly. The original code sni ...

React Hooks do not seem to update accompanying state changes when CSS modifications are made

How can I disable certain sections when a specific button is clicked? Currently, I am trying to achieve this by defining two different CSS properties in the following way: export const useStyles = makeStyles((theme: Theme) => createStyles({ disabl ...

triggering the onsen's setMainPage function when clicked using a variable from ng-repeat loop

I need help customizing my Onsen UI splitView app to dynamically set the main page based on a variable received from a clicked item in a list generated by ng-repeat. After researching ng-repeat and ng-click, I am still unable to achieve the desired outcom ...

Problem with Material-UI Drawer

Is there a way to make this drawer stay fixed on the page like a sticker and remain active without moving when scrolling? I've tried using docked={false}, but it makes the whole page inactive except for the drawer. Any suggestions on how to solve this ...

When using REACT to fetch data from an API, the absence of an 'Access-Control-Allow-Origin' header may result in access issues

I am working on a project that involves retrieving products from a company's API. After reaching out to the company, they provided me with the following information: CORS allowed origins for local development is "http://localhost:1229" To adhere t ...

The error message "Cannot send headers after they have already been sent to the client" is caused by attempting to set headers multiple

Although I'm not a backend developer, I do have experience with express and NodeJS. However, my current project involving MongoDB has hit a roadblock that I can't seem to resolve. Despite researching similar questions and answers, none of the sol ...