Blogs

Blogs

How to use SASS in Angular Widget Liferay

When we generate an Angular Widget project for Liferay DXP from yeoman (liferay-js template), you should realize in the scaffolding, there are assets/{static_folder}/{static_files} and the src/{modules_and_clases}. So at the moment, all static’s file should be put into the assets folder, where you can find for example the CSS file in assets/css folder with the style.css file (set to load on our portlet-header,in your package.json). 

Indeed when this project is generated, 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 SASS doesn't work and you will get an error, for use it you need to install a “sass-loader” and “css-loader”, which you will see 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 “Angular Widget” type and fill in the rest of the information needed:

4. Inside assets/css create a SCSS file “app.component.scss” and add the following style:

     $pink-color: pink;

     .pink-background{

        background-color: $pink-color;

     }

 

5. Open style.css file from asset/css and add the SASS import

     @import 'app.component.css';

 

6. Open app.component.html file from asset/app and add at the first div the class “pink-background” and save it.

7. 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

 

8. 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

 

9. 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"]

}]

 

 10. Now deploy it

npm run deploy

 

11. Add this Angular Project on your Portal Liferay DXP page. It should look like the image below: