Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup react app with SCSS? (Errors)

I am trying to setup my react project so I can use SASS in the SCSS format.

This is in my webpack.config.dev.js:

      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: [
          require.resolve('style-loader'),
          {
            loader: require.resolve('css-loader'),
            options: {
              importLoaders: 1,
            },
          },
          {
            loader: require.resolve('sass-loader'),
          }
        ]
      }

I import the scss files into my jsx in two different ways:

import './index.scss';
import css from './ModalWrapper.scss';

When I run the app I am currently getting the error:

./src/index.scss
Module build failed: 
body {
^
      Invalid CSS after "m": expected 1 selector or at-rule, was "module.exports = __"
      in /pathtoapp/web/src/index.scss (line 1, column 1)

It appears me, that one, react is trying to interpret the SCSS as CSS which should work. In addition, react believes that body is not valid CSS. There, I would believe that neither CSS or SCSS are being loaded correctly.

Any help would be appreciated. There are quite a few unanswered questions to this problem.

like image 606
Programmingjoe Avatar asked Nov 07 '17 19:11

Programmingjoe


1 Answers

If you are on Webpack 3, add this to module.rules

{
    test: /\.scss$/,
    loader: [
      require.resolve('style-loader'),
      require.resolve('css-loader'),
      require.resolve('sass-loader'),
    ]
},

And then add the file loader and make sure to add .scss to the array of the key exclude like this

{
        loader: require.resolve('file-loader'),
        // Exclude `js` files to keep "css" loader working as it injects
        // it's runtime that would otherwise processed through "file" loader.
        // Also exclude `html` and `json` extensions so they get processed
        // by webpacks internal loaders.
        exclude: [/\.js$/, /\.html$/, /\.json$/, /\.scss$/,],
        options: {
          name: 'static/media/[name].[hash:8].[ext]',
        },
}

And of course, make sure you have style-loader, sass-loader, css-loader and file-loader in you package.json. This code snippet worked for me when using the latest version of create-react-app.

like image 126
Swapnil Avatar answered Sep 25 '22 19:09

Swapnil