2

I have a react app with CSS files working fine.
I need to start using SCSS so the following changes:

  1. Install node-sass and sass-loader
  2. Change the imports from .css to .scss
  3. Change file extension from .css to .scss

But my pages are not loading properly:

Current behavior: enter image description here

Expected behavior: enter image description here

My code:

package.json

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@coreui/coreui": "^3.0.0",
    "@stardust-ui/docs-components": "^0.40.0",
    "axios": "^0.19.0",
    "bootstrap": "^4.4.1",
    "compass": "^0.1.1",
    "css-loader": "^3.4.2",
    "mdbreact": "^4.25.4",
    "prettier": "^1.6.1",
    "prop-types": "^15.7.2",
    "react": "^16.10.2",
    "react-bootstrap": "^1.0.0-beta.16",
    "react-bootstrap-sidebar": "0.0.1",
    "react-dom": "^16.10.2",
    "react-fixed-bottom": "^1.0.2",
    "react-modal": "^3.11.1",
    "react-rangeslider": "^2.2.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "^1.1.5",
    "reconnecting-websocket": "^4.2.0",
    "reconnectingwebsocket": "^1.0.0",
    "semantic-ui-react": "^0.88.2",
    "style-loader": "^1.1.3",
    "styled-components": "^4.4.1"
  },
  "scripts": {
    "start": "PORT=3000 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "node-sass": "^4.13.1",
    "sass-loader": "^8.0.2"
  }
}

I injected the code for the loaders in node_modules/react-scripts/config/webpack.config.dev.js like this:

// Process JS with Babel.
          {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              // @remove-on-eject-begin
              babelrc: false,
              presets: [require.resolve('babel-preset-react-app')],
              // @remove-on-eject-end
              // This is a feature of `babel-loader` for webpack (not Babel itself).
              // It enables caching results in ./node_modules/.cache/babel-loader/
              // directory for faster rebuilds.
              cacheDirectory: true,
            },
          },
          { 
            test: /\.scss$/, 
            loader: [
              "css-loader",
              "sass-loader"
            ]
          },

Here is my component:

import React, { Component } from "react";
import '../../../general.scss';
import { Warning } from '../../../images/images_svg';

class Terminos extends Component{
  state = { error: false }

  saveAndContinue = () => {
    if(this.props.values.terminos) {
       this.props.nextStep()      
    }
    else {
       console.log(this.props.values.terminos_error)
       this.props.mandar_error('terminos_error')
    }     
  }

  render() { 
    return (
      <div className="formulario">
        <div className="formulario-seccion-titulo">
          <div className="formulario-seccion-barrita"/>
            <div className="formulario-seccion-content">
               Presentacion
            </div>
          </div>      
          <div className={this.props.values.terminos_error ? "formulario-seccion" : "formulario-seccion-red"}>
             La actual pandemia que afecta al mundo trae consecuencias a nivel sanitario, económico y social. Lo que está ocurriendo con el COVID impacta de lleno, no sólo en la salud física de las personas, sino que también afecta de forma clara y contundente su salud mental.<br/><br/>
             Ud. puede decidir si contestar o no la encuesta que sigue pero de hacerlo,acepta que los resultados de la misma sean compartidos con su empleador con el único fin de brindarle contención y asistencia. La encuesta debe completarse en las próximas 10 horas.<br/><br/>
             <input type="checkbox" 
               id="terminos" 
               className="formulario-checkbox"
               onChange={() => this.props.handleTerminos()}
               checked={this.props.values.terminos}
             />  
             <label className="formulario-checkbox-label" htmlFor="terminos"> 
               Acepto terminos y condiciones.
             </label>
             {this.props.values.terminos_error===false &&
                <div className="formulario-seccion-error">
                  <div className="formulario-seccion-error-logo" >
                    <Warning color="#d93025"/>
                  </div>
                    Debes aceptar los terminos y condiciones para continuar
                </div>
              }
           </div>
           <div className="formulario-footer">
             <button className="formulario-botones" onClick={this.saveAndContinue}>Siguiente</button>
           </div>
         </div>
       )    
    }
}

export default Terminos;

If I change the import and the file extension from .scss to .css the page load properly.
I´m using npm start to develop and testing the code.

Jee Mok
  • 6,157
  • 8
  • 47
  • 80
Knemay
  • 350
  • 1
  • 6
  • 12

3 Answers3

0

Have you created project with Create-React-App? In this case, you don't need sass-loader, you just need node-sass, and import your CSS style into your root file with .scss/sass extension, for example, import '../example.scss', then need to configure webpack.config.js at all.

Please provide more information.

Have a nice day.

BloodOverdrive
  • 301
  • 1
  • 3
  • 15
  • Yes, i have created the project with Create-React-App. I´m importing the scss files as you said (check the component code in the question). The path is correct as no erros are shown, and if I change the import and the file extension from .scss to .css the page load properly. – Knemay Apr 04 '20 at 18:30
  • Do you use a third-party CSS framework or something jquery related? – BloodOverdrive Apr 04 '20 at 20:33
  • In fact, am actually wondering, if you used `create-react-app` to kick-start your project then `Webpack` should already have been configured. – MwamiTovi Apr 05 '20 at 13:14
  • I used `create-react-app`, then i created the webpack.config.js because i´m having this issue – Knemay Apr 05 '20 at 18:12
  • Ok, so we are dealing with a deeper challenge. If you're still using `npm start` to launch your app, then I hope you are aware that it actually uses `react-scripts` which has a `Webpack config`. So unless you run `npm eject`, I believe your own `Webpack config` isn't being read at all by `react`. It explains why `.css` is loaded while `.scss` isn't. We now need to address if your introduced `node-sass` and `sass-loader` the right way. For one, having worked with `SCSS`, am aware that there's a lot of version issues as concerns `node-sass`. Did you get any warning at installation? – MwamiTovi Apr 05 '20 at 18:37
  • I think we are on the right track here. I added sccs in the extension line: `extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx','scss'],` and this in the rules line: `{ test: /\.scss$/, loader: [ "css-loader", "sass-loader" ] },`. Still not working, but if i uninstall sass-loader the command `npm start` fails with error code: Module not found: Can't resolve 'sass-loader' – Knemay Apr 05 '20 at 23:03
  • For a better review, kindly update your QUESTION with the latest changes. Including what has been updated in the `package.json` and within your `Webpack.config`. – MwamiTovi Apr 06 '20 at 02:06
  • ok, i updated my question with the lastest changes. Could it be that there is something wrong with the way i introduced the loaders in the webpack.config.dev.js – Knemay Apr 07 '20 at 19:51
0

Webpack has seen tremendous changes up until version 4

When we use create-react-app, it installs a compatible version of Webpack that react-scripts utilizes to bundle your files and serves them using Webpack-server as the dev server when you run npm start.

  • Remove "webpack": "^3.11.0" from your package.json since it's already installed by react-scripts.

  • Also react 16+ often works with react-scripts 3+ so if you manually edited some of this package.json file, i recommend you leave the defaults installed by create-react-app and just add your other dependencies.

Otherwise, here's What Webpack says about loaders.

MwamiTovi
  • 2,425
  • 17
  • 25
  • Ok, i modify the webpack config, the result is the same, thx anyway – Knemay Apr 05 '20 at 18:14
  • Please see my updated answer to this issue. If you stick to the approach of `create-react-app`, just installing `node-sass` and `sass-loader` should be enough for this to work. – MwamiTovi Apr 05 '20 at 19:26
0

Ok, I solved it deleting the node-modules folder, the package-lock.json and all my dependencies in the package.json. Then I reinstalled all my dependencies with npm install .... I think the problem was the react-scripts module, i upgraded from version 1.1.5 to 3.4.1 . Thank you all for your answers.

Knemay
  • 350
  • 1
  • 6
  • 12