6

I'd like to build a project with CSS modules + SASS. I'd like to have some global styles (mixins, variables, functions etc), that will be available in every component.module.scss. For that I need to import my global styles to every single module style file. As I expect to have a lot of components, I was looking for options to do this automatically. I've found sass-resourcess-loader ,might help with that.

However, as I don't have any experiencies with Webpack, I have troubles to setting it up.

What I did so far:

  1. Created my react app with create-react-app
  2. Installed node-sass and sass-resources-loader
  3. In my project-folder/node_modules/react-scripts/webpack.config.js on line 595 I've added

{ test: /.scss$/, use: [ { loader: "style-loader", }, { loader: "css-loader", }, { loader: "sass-loader", }, { loader: "sass-resources-loader", } ], }

Sorry I cannot get that code snippet styled properly somehow. Also I've tried options field:

options: {
 resources: "./src/global.scss"
}

But nothing works, I still get undefined variable in my modular scss file.

What am I doing wrong? Or is there another way to resolve this problem?

1 Answer 1

9

Okay so I've find solution with CRACO (Create React App Configuration Override).

1) I've uninstalled sass-reasources-loader as is not needed anymore and reverted the changes in webpack.config.js

2) Installed CRACO and craco-sass-resources-loader

3) Created craco.config.js file inside root directory of my project and added this:

const sassResourcesLoader = require("craco-sass-resources-loader");

module.exports = {
    mode: "development",
    output: {
        path: __dirname,
    },
    plugins: [
        {
            plugin: sassResourcesLoader,
            options: {
                resources: "./src/global.scss",
            },
        },
    ],
};

4) In package.json I've changed the scripts to:

"start": "craco start",

"build": "craco build",

Now everything works. If you need more info, click on the links provided in step 2.

Sign up to request clarification or add additional context in comments.

1 Comment

Anyone who is using typescript with cra can get Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser. using eslint for linting purpose. They can follow this thread for solving their error stackoverflow.com/questions/58510287/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.