0
votes

My package.json has the following scripts:

I have the following CSS in styles.css (I am only using one CSS file):

    .btn {
        @apply rounded py-2 px-4;
    }
    .btn.xs {
        @apply px-1;
    }
    .btn.sm {
        @apply py-1 px-2;
    }
    .btn.md {
        @apply py-2 px-4;
    }


    .btn.normal {
        border: 2px solid #A8A878;
        color: #000;
    }
    .btn.normal:hover {
        background-color: #A8A878;
        color: #FFF;
    }
    .btn.normal:focus {
        --tw-ring-shadow: 0 0 0 2px #A8A87844;
    }
    "scripts": {
        "dev-no-watch": "postcss src/styles.css -o dist/css/styles.css",
        "dev": "postcss src/styles.css -o dist/css/styles.css --watch",
        "build": "cross-env NODE_ENV=production postcss src/styles.css -o dist/css/styles.css && cleancss -o dist/css/styles.css dist/css/styles.css"
    },

Running the dev script works fine, and the generated code has all of my styles.

Running the build script runs without errors, however, it removes part of my styles, which I find mind-boggling. My .btn styles are applied, but my .btn.normal styles are not.

I figured this was due to the --tw-ring-shadow property getting cleaned by cleancss, but removing the cleancss part of the build script it still has the same problem. Removing cross-env NODE_ENV=production solves the problem, but obviously I'd like to minify the file for production.

A friend warned that:

If your CSS file has the Tailwind references then it'll be running purge css as part of the build process. If that's happening you can avoid that by reordering the file as explained here

And linked me here:

https://tailwindcss.com/docs/optimizing-for-production#removing-all-unused-styles

However my tailwind.config.js should be fine:

module.exports = {
    purge: [
        './dist/**/*.html',
        './dist/**/*.js'
    ],
    darkMode: false, // or 'media' or 'class'
    theme: {
        extend: {},
    },
    variants: {
        extend: {},
    },
    plugins: [],
}

and here's my postcss.config.js for posterity:

module.exports = {
    plugins: [
        require('tailwindcss'),
        require('autoprefixer')
    ]
};

Some links I've looked at:

1

1 Answers

2
votes

My friend helped me find this one. purgecss removes classes it doesn't see in the html. My JS was dynamically adding buttons to the page with the classes, and purgecss didn't see them so it removed them. Adding them to an item with class hidden works

<span class="hidden normal"></span>

Purgecss also has a whitelist option which I'll be using. Hope this answer helps anyone who is getting their custom styles removed by purge when dynamically inserting elements.

Edit: link to puprgecss safelist docs: https://purgecss.com/safelisting.html