How to use the LESS preprocessor in React Create-React-APP

I want to use the LESS preprocessor in my create-react-app.

React Code ReactDOM.render( <form> <input type="email" data-info="Enter Email" pattern="/\ S+@ \S+\.\S+/" required title="Please enter value" required="required"/> <input type="submit"/> </form> ,document.getElementById('root')) 

index.less

 body{ background: red; } 
+5
source share
2 answers

This is how i do it

You should use the node-sass-chokidar npm package:

 npm install node-sass-chokidar --save-dev 

Then add the following to your npm scripts in package.json:

 "build-css": "node-sass-chokidar src/ -o src/", "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive" 

The watcher will find each Sass file in the src subdirectories and create the corresponding CSS file next to it.

Remember to delete all css files from the source control and add src / ** / *. css in .gitignore.

Finally, you can run watch-css automatically with npm running and run build-css as part of the npm run assembly. To do this, install the following npm package to be able to run two scripts in sequence:

 npm install --save-dev npm-run-all 

Then change the npm startup and build scripts in the package.json file to the following:

  "scripts": { "build-css": "node-sass-chokidar src/ -o src/", "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive" "start-js": "react-scripts start", "start": "npm-run-all -p watch-css start-js", "build": "npm run build-css && react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } 

See this link for more information: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-a-css-preprocessor-sass -less-etc

+2
source

The easiest and most painless way to add less support using the reactjs application is to use custom-react-scripts with create-react-app to support LESS / SASS / decorators:

Install: npm install -g create-react-app custom-react-scripts

Create application: create-react-app <app_name> β€”scripts-version custom-react-scripts

An example of a smaller file:

 .myDiv{ background: gray; } 

and then in your component:

 import lessStyles from '<less file path>'; <div style={lessStyles.myDiv}> ... </div> 

or in the usual way:

 import '<less file path>'; <div className="myDiv"> ... </div> 

For reference:

https://github.com/kitze/custom-react-scripts

https://github.com/fawaz-ahmed/fawaz-ahmed.imtqy.com

+1
source

Source: https://habr.com/ru/post/1268295/


All Articles