lunes, 30 de agosto de 2021

create-react-app and SASS structure project

create-react-app and SASS structure project

 
When we want to setup a React project and use SASS, at this time following the instructions from oficial react page, have a compativility problem, so. the alternative right way and tested is described.
 
1. Do all the needed steps to setup a normal React App using create-react-app
 
npx create-react-app
 
2. install SASS
 
$npm i sass

Once installed, at this point our package.json looks like this, adding the sass dependency

{
  "name""my_react_app_sass",
  "version""0.1.0",
  "private"true,
  "dependencies": {
    "@testing-library/jest-dom""^5.14.1",
    "@testing-library/react""^11.2.7",
    "@testing-library/user-event""^12.8.3",
    "react""^17.0.2",
    "react-dom""^17.0.2",
    "react-scripts""4.0.3",
    "sass""^1.38.1",
    "web-vitals""^1.1.2"
  },
  "scripts": {
    "start""react-scripts start",
    "build""react-scripts build",
    "test""react-scripts test",
    "eject""react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}


 
run the project 
 
npm start
 
Now prepare our file structure to add the scss file. Create a directory called scss, and add the file app.scss
 
src/scss/app.scss
 
Now we are ready to add scss code or sass code. In the App.js file, we change the css import for the ./scss/app.scss and now for test just change the background color.
 
app.scss file
 
body {
    backgroundgreen;
}
 
App.js file 
 
import logo from './logo.svg';
import './scss/app.scss';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;
 
Browser output:

Also works for .sass extensions, lets change the app.scss to app.sass, and thier syntax.

app.sass

body 
    background: green

 
And change the import in App.js file
 
 
 
eot

No hay comentarios:

Publicar un comentario