Angular, how to optimize scss compilation
The scss compilation is very slow on large angular projects.
In my case, I have a project with a lot of scss files. This slows down the build considerably, to the point of exceeding 10 minutes before I can write a single line of code.
After analyzing the cpu node consumption, I noticed that the modules used by angular-cli to transpile the scss to css were sass-loader and url-resolve-loader.
After some research, I found the fast-sass-loader transpiler which now replaces sass-loader and url-resolve-loader.
This allowed me to divide by 3 the compilation time of my angular project.
To overload the angular compilation with fast-sass-loader, I used the recipe below.
Install dependencies :
npm i -D @angular-builders/custom-webpack
npm i -D @angular-builders/dev-server
npm i -D node-sass@4.12
npm i -D fast-sass-loader
Note : if you have an angular 10 version, you will have to install custom-webpack with version 10 :
npm i -D angular-builders/custom-webpack@10.0.0
Change the angular.json file :
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./custom-webpack.config.js",
"replaceDuplicatePlugins": true
}
}
}
}
"serve": {
"builder": "@angular-builders/custom-webpack:dev-server"
}
At the root of your project, create a custom-webpack.config.js
I could not use ‘~’ in my scss imports with fast-sass-loader. In order to fix that, I have used includePaths:[‘src/scss’] (see above). It is were all my scss partials are stored. It tells to fast-sass-loader to prepend src/scss to all the scss imports used in my components.
All my scss component files use imports like this when they need the partials :
@import 'table';
Here table is a partials that is located in src/scss/_table.scss.
Now, my build time compilation is really faster. Also, the bundle size have reduced a lot.