angularwebpackangular-clicss-purge

How to integrate PurgeCSS with Angular CLI project


I have an Angular project created with Angular CLI, so I have angular.json file for configuring the build.

I wanted to integrate PurgeCSS as it seems to be a great tool to reduce the size of our CSS bundle.

On PurgeCSS website, they explain how to integrate with Webpack. I found a tutorial that explains how to add custom webpack integration with Angular CLI.

Did anyone have a successful example of PurgeCSS integrated with Angular CLI project ?


Solution

  • I created this bash script to use PurgeCSS with my Angular app. It reduced my 'styles.css' file size from 63kb to only 3kb! Hope it works for you too.

    Steps:

    1. create a new file named purgecss.sh inside your project folder
    2. insert the code below into purgecss.sh file
    3. run ./purgecss.sh from CLI
    #!/bin/bash
    
    # run production build
    ng build --prod --output-hashing none
    
    # go to the dist/yourProjectName folder
    cd ./dist/yourProjectName
    
    # make a new directory named 'css' (you can name it anything)
    mkdir css
    
    # run PurgeCSS & make a new '.css' file inside the 'css' directory
    purgecss --css ./styles.css --content ./index.html ./*.js --out ./css
    
    # replace the 'dist/yourProjectName/styles.css' file with the 'dist/yourProjectName/css/styles.css' file
    mv ./css/styles.css ./styles.css
    
    # delete the previously created 'css' directory
    rm -r css