How to integrate PurgeCSS with Angular CLI project

前端 未结 4 2031
后悔当初
后悔当初 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:06

    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

提交回复
热议问题