Tonio
Tonio

Reputation: 5044

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 ?

Upvotes: 17

Views: 17649

Answers (5)

Oleksandr Poshtaruk
Oleksandr Poshtaruk

Reputation: 2166

I found good answer here - and no need to apply custom-webpack config

Steps:

  1. npm i purgecss

  2. Add command to package.json->scripts "postbuild": "node postbuild.js",

  3. And create script postbuild.js in project root folder with such content

    // "postbuild": "node environments/postbuild.js", // from https://dev.to/dylanvdmerwe/reduce-angular-style-size-using-purgecss-to-remove-unused-styles-3b2k

    const exec = require('child_process').exec; const fs = require('fs'); const path = require('path');

    // find the styles css file const files = getFilesFromPath('./dist', '.css'); let data = [];

    if (!files && files.length <= 0) { console.log("cannot find style files to purge"); return; }

    for (let f of files) { // get original file size const originalSize = getFilesizeInKiloBytes('./dist/' + f) + "kb"; var o = { "file": f, "originalSize": originalSize, "newSize": "" }; data.push(o); }

    console.log("Run PurgeCSS...");

    exec("purgecss -css dist/.css --content dist/index.html dist/.js -o dist/", function (error, stdout, stderr) { console.log("PurgeCSS done"); console.log();

    for (let d of data) { // get new file size const newSize = getFilesizeInKiloBytes('./dist/' + d.file) + "kb"; d.newSize = newSize; }

    console.table(data); });

    function getFilesizeInKiloBytes(filename) { var stats = fs.statSync(filename); var fileSizeInBytes = stats.size / 1024; return fileSizeInBytes.toFixed(2); }

    function getFilesFromPath(dir, extension) { let files = fs.readdirSync(dir); return files.filter(e => path.extname(e).toLowerCase() === extension); }

  4. In script correct path fo built project (if it is not /dist but /dist/projectName)

  5. It will automatically run after build or you can run it manually with npm run postbuild.

Upvotes: 0

Jan Kuri
Jan Kuri

Reputation: 1067

This configuration works for me and giving me results from 126kb to 34kb on my styles.[hash].css output for production build.

First, install this:

npm install -D @angular-builders/custom-webpack purgecss-webpack-plugin

Then, create webpack.config.js in the root of the project:

const glob = require('glob');
const PurgeCSSPlugin = require('purgecss-webpack-plugin');

module.exports = {
  plugins: [
    new PurgeCSSPlugin({ paths: glob.sync('./src/**/*.html', { nodir: true }) })
  ]
};

and edit your angular.json configuration as follows:

"architect": {
   "build": {
     "builder": "@angular-builders/custom-webpack:browser",
     "options": {
       "customWebpackConfig": {
         "path": "webpack.config.js"
       },
       ...

My result without this plugin:

styles.ca3c7399cc89e60cfa2d.css   | styles        | 128.99 kB

And now with the purgecss-webpack-plugin:

styles.ca3c7399cc89e60cfa2d.css   | styles        |  34.46 kB

Which is amazing, first when I saw this output I went checked my app in the browser and all styles have been included properly :-).

Only downside may be that this doesn't work on inlined html if any in angular components, I think.

Upvotes: 19

Jabir Minjibir
Jabir Minjibir

Reputation: 137

You can simply run the following commands in your project root directory

npm i -D postcss-import postcss-loader postcss-scss
ng add ngx-build-plus

In angular.json, make the following replacements in "architect" section:

"builder": "@angular-devkit/build-angular:browser" with "builder": "ngx-build-plus:browser" under "build",

"builder": "@angular-devkit/build-angular:dev-server" with "builder": "ngx-build-plus:dev-server" under "serve",

"builder": "@angular-devkit/build-angular:karma" with "builder": "ngx-build-plus:karma" under "test",

You should also add "extraWebpackConfig": "webpack.config.js" under options in the respected sections.

Upvotes: 3

Joao Edmundo
Joao Edmundo

Reputation: 439

There is another way which is more in line with Angular CLI and Webpack config:

You need to install

npm install -D @angular-builders/custom-webpack postcss-scss @fullhuman/postcss-purgecss

Then create a webpack.config.js config file:

const purgecss = require('@fullhuman/postcss-purgecss')

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        loader: 'postcss-loader',
        options: {
          ident: 'postcss',
          syntax: 'postcss-scss',
          plugins: () => [
            require('postcss-import'),
            require('autoprefixer'),
            purgecss({
              content: ['./**/*.html'],
              // Example to let PurgeCss know how to exclude cdk and mat prefixes if your using Angular CDK and Angular Material
              whitelistPatterns: [/^cdk-|mat-/]
            })
          ]
        }
      }
    ]
  }
};

Then change your angular.json file to use this new configurations:

...
"build": {
  "builder": "@angular-builders/custom-webpack:browser",
  "options": {
    "customWebpackConfig": {
      "path": "webpack.config.js"
    },
    ...
  }
},
...

Make sure you run this configuration only in production mode, when you bundle the final application.

Hope this helps.

I created a post to explain how in detail - https://medium.com/@joao.a.edmundo/angular-cli-tailwindcss-purgecss-2853ef422c02

Upvotes: 32

S N Sakib
S N Sakib

Reputation: 1172

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

Upvotes: 22

Related Questions