Search code examples
cssreactjswebpacksasswebpack-4

How to setup Webpack using Create-React-App for sass-resources-loader?


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?


Solution

  • 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.