why I can't update my css file via purgecss?

134 views Asked by At

I'm implementing a mini CSS library with SASS and I want to purge that, currently I'm using purgecss and I have no issue with that but one problem is that when I add a class to my html from my CSS library, that specific class doesn't get included in my purged file and I need to repurge my CSS library CSS file to include that specific class but I need to purgecss watches my CSS file and add classes while I'm adding it to my project and I don't need to repurge my CSS file, so any idea?

1

There are 1 answers

1
Philipp Sander On

To dynamically include classes from your CSS library without having to manually repurge the CSS file, you can use a combination of PurgeCSS and an additional configuration file for PurgeCSS to watch your CSS file and include specific classes.

Here's how you can set it up:

  1. Create a PurgeCSS configuration file: Start by creating a separate configuration file for PurgeCSS, let's call it purgecss.config.js. This file will specify the files to be purged and any additional configuration options.
// purgecss.config.js

module.exports = {
  content: ['index.html'], // Specify your HTML files here
  css: ['path/to/your/css/library.css'], // Path to your CSS library file
  defaultExtractor: content => content.match(/[A-Za-z0-9-_:/]+/g) || [], // Default extractor, modify if needed
  safelist: ['class-to-include'], // Add classes that should always be included here
};
  1. Configure your build process: You need to configure your build process to watch your CSS file and trigger PurgeCSS whenever changes occur. You can use tools like Webpack, Gulp, or Grunt to accomplish this. Here's an example using Webpack:
// webpack.config.js

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

module.exports = {
  // ... other webpack configuration options

  plugins: [
    new PurgecssPlugin({
      paths: () => glob.sync(path.resolve(__dirname, 'index.html')), // Specify your HTML files here
      safelist: { deep: [/^class-to-include$/] }, // Add classes that should always be included here
    }),
  ],
};
  1. Start your build process: Now, whenever you add a class from your CSS library to your HTML files, the build process will automatically watch for changes and trigger PurgeCSS to include the specific class you added.

Make sure to adjust the paths and file names in the code snippets above to match your project structure. Additionally, if you're using a different build system or tool, you may need to adapt the configuration accordingly.

With this setup, you won't need to manually repurge your CSS file every time you add a class from your CSS library to your project. Instead, PurgeCSS will watch for changes and include the classes dynamically during the build process.