How to integrate PurgeCSS with Angular CLI project

前端 未结 4 1988
后悔当初
后悔当初 2021-02-04 13:30

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

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-04 14:18

    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.

提交回复
热议问题