5

Followed the link https://mattferderer.com/use-sass-variables-in-typescript-and-javascript

Looking to access the scss varaibles in react component . Not sure with what import name i need to call in react component since if i give as below import statement it is showing an error as cannot find the module '../scss/_variables.scss';

import _variables from '../scss/_variables.scss';

here _variables.scss is the file name which contains

 // variables.scss
$white-color: #fcf5ed; 

:export {
  whitecolor: $white-color; }

I am scratching my head to get the "whitecolor" variable available in react component .

Also, I am using webpack as below

{
 test: '/.scss$/',
 use: [{
  loader: 'style-loader' // creates style nodes from JS strings
 }, {
  loader: 'css-loader' // translates CSS into CommonJS
 }, {
  loader: 'sass-loader' // compiles Sass to CSS
 }]
}

enter image description here

Any help would be highly appreciated!!

Martin
  • 5,714
  • 2
  • 21
  • 41
Srinu Merugu
  • 103
  • 2
  • 7
  • 1
    Did you manage to resolve the issue? I have a similar problem and looking for a solution... – desa Apr 03 '21 at 13:57
  • 1
    I have used "require" to make it work . const variables = require('../scss/_variables.scss'); – Srinu Merugu Apr 05 '21 at 06:24
  • I see. But did you make it work with `import`? – desa Apr 05 '21 at 14:32
  • 1
    Below accepted answer from @yatin to use import works. I am using minicssextractplugin with webpack 5. And minicssextractplugin stopped supporting require module from 1.0.0 version. So, I had to use import rather than require module now. – Srinu Merugu Apr 08 '21 at 16:31

3 Answers3

11

Importing specific property in React does not work unless it is a module.

I was facing the same problem and here is what I did:

Renamed _variables.scss to _variables.module.scss and then the import is import _variables from '../scss/_variables.module.scss';

now you can access the scss variables just like _variables.whitecolor

Yatin Gaikwad
  • 1,140
  • 1
  • 13
  • 23
-1

On the react app, you can import the variable.scss in App.scss file. If there is no file just create it.

make sure that you have installed node-sass.

@import "../scss/_variables.scss";

Now the variables are accessible, I am using React Webpack. Also, we have other options please check here

Thanks, Prem

Premji
  • 69
  • 1
  • 6
-2

One way would be to npm install node-sass

Then change your app.css to app.scss and in there you import your stylesheet:

@import '../scss/_variables.scss';

Then you can use it like

.App-link {
  color: $secondary-color;
}
Jake
  • 712
  • 7
  • 20
  • 2
    I want to access the scss variables in typescript/js files not inside the other scss files . Your solution works for passing variables in scss files . – Srinu Merugu Aug 02 '19 at 05:34