G'day,
I am building a React component library with TailwindCSS and ViteJS. The library outputs each component as a separate JS file, for example:
// @components-library/src/ComponentA.jsx
export default function ComponentA() {
return <div className="flex justify-center">Component A</div>;
}
// Bundle Output: @components-library/dist/ComponentA.js
import { j as jsx } from "./jsx-runtime.js";
import "react";
function ComponentA() {
return /* @__PURE__ */ jsx("div", {
className: "flex justify-center",
children: "Component A",
});
}
export { ComponentA as default };
The app that is consuming this components library is also using Tailwind. However, the styles are not applied to the imported component. App-specific styles are working fine.
/* app/src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
// app/src/App.jsx
import CompoenntA from "@component-library/ComponentA";
export default function App() {
return (
<div className="p-10">
<ComponentA />
</div>
);
}
Awaiting expert advice.
Thank you!
Currently, I am also working on a similar project as like as you. I have built my component library with rollup. It generated a CSS file then imported that CSS file to my main package.
import resolve from "@rollup/plugin-node-resolve";
import babel from "@rollup/plugin-babel";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import { terser } from "rollup-plugin-terser";
import external from "rollup-plugin-peer-deps-external";
import postcss from "rollup-plugin-postcss";
import swc from "rollup-plugin-swc";
import filesize from "rollup-plugin-filesize";
const packageJson = require("./package.json");
export default [
{
input: "index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: false,
name: "@ht/components",
},
{
file: packageJson.module,
format: "esm",
sourcemap: false,
},
],
plugins: [
babel({
// this is needed because we're using TypeScript
babelHelpers: "bundled",
extensions: [".ts", ".tsx"],
}),
external(),
resolve(),
commonjs(),
typescript({ tsconfig: "./tsconfig.json" }),
postcss({
config: {
path: "./postcss.config.js",
},
extensions: [".css"],
minimize: true,
extract: "lib.css",
}),
swc({
jsc: {
parser: {
syntax: "typescript",
},
target: "es2018",
},
}),
terser(),
filesize(),
],
},
];
import "@ht/components/dist/cjs/lib.css";
import "./assets/css/tailwind.css";
You should add the path of the component to the tailwind.config.js.
In my case, my component library is symlinked to the current project using yarn link and the same problem was happening. Here is what I added in tailwind.config.js:
module.exports = {
// use content instead of purge if using tailiwind v3
purge: [
"./src/**/*.{js,jsx,ts,tsx}",
"./public/index.html",
// this line fixed the issue for me
"./node_modules/{component-library-name}/src/**/*.{js,jsx,ts,tsx}"
],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {}
},
variants: {
extend: {}
},
plugins: []
};