reactjsnpmtailwind-cssrollup

Unable to Package React Component with Tailwind using Rollup for NPM


Context:

I am trying to create an NPM package for a React component that incorporates Tailwind CSS. The HTML of the component displays correctly when the package is installed, but the Tailwind styles are not applied. I have no issues packaging a React component without Tailwind.

The Issue:

Upon using Rollup to bundle the component along with Tailwind, I observed that while the HTML is correctly rendered, the Tailwind styles are missing. On deeper inspection, I noticed that the style script, which should be embedded in the of the web page by styleInject(), seems to be truncated in DevTools. There's a possibility that DevTools might be visually truncating it, so I'm unsure if the issue lies there.

Relevant Code:

I've shared the repositories containing the code below. Some key areas that might be helpful for debugging include the package.json and rollup.config.js files.

https://github.com/adam-zakaria/vite-react-package-styled-install-here

https://github.com/adam-zakaria/vite-react-package-styled

https://www.npmjs.com/package/vite-react-package-styled?activeTab=code

Request:

I've been wrestling with this problem for some time and would truly appreciate any guidance or solutions the community might provide. If you've done this before and can share your rollup.config.js that may help.


Solution

  • In the rollup config change:

    modules: true,  // Use CSS modules
    

    To

    modules: false,
    

    Then build the project again, publish it, update the consuming project, and try again.

    Tailwind uses global class names by design and having CSS modules on is scoping the classes, which makes no sense here.

    By the way, Vite is already based on rollup. You don't really need both in your project. Consider Vite library mode.