How to use SASS in React Widget Liferay

In a native React application, it is common that you have the CSS separated by components like I said here, actually maybe you want to use a separate SCSS to take advantage from SASS. So to do it in a Liferay React Application, we need to do some configurations. 

Why? 

We are working a Structure of OSGi Bundles Containing NPM Packages wrapper by Portlet Component, for this reason, by default you have this style.css loaded by a portlet-header, and if you try to use a separate CSS or SASS file by component doesn't work and you will get an error. 

So basically always when a developer wants to add new styles always needs to be put on assets/css/style.css file right? Not all... so you should be asking for “how can I have my components and scss modularized in this React Widget?” The answer is with “sass-loader” and “css-loader” and in this tutorial you will know the few steps to do it.

Requirements: Node, Yeoman and NPM Installed

1. First, it is necessary to install liferay-js by running this command:

npm install -g generator-liferay-js

  

2. Run the generator inside your “liferay-workspace/modules” or some other project folder which you are using

yo liferay-js

  

3. Choose the “React Widget” type and fill in the rest of the information needed:


 

4. Inside src create a CSS file “AppComponent.scss” and add the following style:

$pink-color: pink;

.pink-background{

    background-color: $pink-color;

}

 

5. Open AppComponent.js file from source and add at the first div the className “pink-background” and save it.

6. Now we need to install the liferay-npm-bundler-loader-sass-loader, which will run a sass or node-sass from your project and convert a SASS or SCSS file to CSS files.

npm install --save-dev liferay-npm-bundler-loader-sass-loader

  

7. Now we need to install the liferay-npm-bundler-loader-css-loader, which will convert CSS files to JavaScript modules and when the application is on the page will download it as CSS files from the server.

npm install --save-dev liferay-npm-bundler-loader-css-loader

 

8. Now to do the configuration for works the CSS by URL you need to set the “source” and “rules” in .npmbundlerrc, adding the follow it code 

"sources" : ["src", "assets"],

"rules": [

{

"test": "\\.scss$",

"use": ["sass-loader","css-loader"]

}]

 

 9. The final .npmbundlerrc should look like this:


 

10. Now deploy it

npm run deploy

 

11. Add the application to Liferay Portal’s page and now it should look like the image below: