Jimmy
Jimmy

Reputation: 3860

How to use import global sass variables with create-react-app (ejected)

Please see this repo for further information and reproduction.

I am using an ejected create-react-app and I want to be able to use global sass variables in an individual stylesheet without having to import the stylesheet. I think using sass-resources-loader is what I should use (although if there is a better way of doing this, please let me know). I have updated the create-react-app ejected webpack config here, but whenever I run yarn start, I still get the complaint:

SassError: Undefined variable: "$boxSize". on line 5 of src/SampleComponent/sampleComponent.scss , height: $boxSize;

Is there something that I am doing wrong in trying to use sass-resources-loader or should I be using something different instead? Thanks, and here are some file snippets below for more context:

file structure:

src/
  - SampleComponent/
    - SampleComponent.js
    - SampleComponent.scss
  - styles/
    - sizes.scss
  - index.js  

SampleComponent.js:

import * as styles from './sampleComponent.scss';

const SampleComponent = () => (
  <div className={styles.div}>
    <h3>hello world</h3>
  </div>
);

export default SampleComponent;

sampleComponent.scss:

.div {
  align-items: center;
  background: pink;
  display: flex;
  height: $boxSize;
  justify-content: center;
  margin: 5rem;
  width: $boxSize;
}

sizes.scss:

$boxSize: 30rem;

Upvotes: 1

Views: 1187

Answers (1)

Grzegorz T.
Grzegorz T.

Reputation: 4113

Use the sass-loader library, I use it that way and it works very well.

{
  loader: 'sass-loader',
  options: {
    sourceMap: true,
    additionalData: `
        @import "sources/scss/modules/_config.scss";
        @import "sources/scss/modules/_global.scss";
      `
  },
},

Upvotes: 1

Related Questions