Purging TailwindCSS classes from custom npm package

Hi,

I’ve built a custom node package for use on a group of sites that I’m building. Within the custom node package I have used TailwindCSS classes. I’ve added the following line to my tailwind.config.js purge array:

'./node_modules/my-node-package/src/**/*.{vue,js}'

This is working locally in that all of the classes I’ve used in my package are not purged when I run npm run generate. On Netlify, it does not work, and all of the classes that are not used elsewhere are purged.

Thank you in advance for your help.

hi @ThomCM - sorry to be slow to reply and I also have to unfortunately say I don’t have a straightforward answer for you. We don’t know a ton about purgecss, but there are some threads on it in these forums already that might be helpful:

https://answers.netlify.com/search?q=purgecss

if you figure out the solution, would you mind sharing it here so others can benefit?

Hi Perry

I don’t see this as a purgecss-specific issue as the above mentioned code works when npm run generate is run locally, but not through Netlify.

I give it this path './node_modules/my-node-package/src/**/*.{vue,js}' which is requesting “look for css classes at this location and if you find them, do not purge them”. I’m guessing it’s just the wrong path.

I was in a rush so I just ended up replacing the Tailwind classes with custom css classes that wouldn’t get purged.

You should not reference node_modules directly, you should always resolve it via require.resolve('my-node-package'). Also, use path.join.

i.e. you tailwind config should look like

const path = require('path')
const packagePath = require.resolve('my-node-package')
const purgePath = path.join(packagePath, 'src', '**', '*', '*.')
module.exports = {
  // your other tailwind settings
  purge: [ /* your local files */, purgePath + '{vue,js}' ]
}
1 Like

I think require.resolve will return a path including the filename. To get the path only use:

const packagePath = path.dirname(require.resolve('my-node-package'))

See Modules: CommonJS modules | Node.js v19.4.0 Documentation

However, in my case, my package was scoped, and the only thing that worked for me was escaping the @ symbol:

module.exports = {
  // your other tailwind settings
  purge: ['./src/**/*.tsx', './src/**/*.styled.tsx', './node_modules/\\@org/component-library/dist/*.js']
}