reactjstailwind-cssvitetailwind-css-4

Tailwind v4 CSS Variables Not Recognized when bundled


We have a component library built with Vite's library mode, which uses Tailwind v4 for styling. The library defines custom colors via CSS variables, and everything works correctly within the library itself.

However, when we use this component library in another project (bundled with vite), the custom colors are not being recognized. It seems like the CSS variables are either missing or not being applied properly.

brand-orange-900 for example doesn't work when using the library.

Has anyone encountered this issue before? Any insights on how to ensure Tailwind's CSS variables are correctly included when using a library built with Vite?

Versions:

vite.config.js

export default defineConfig({
  plugins: [
    react(),
    dts({
      tsconfigPath: './tsconfig.app.json',
      exclude: ['src/components/**/*.stories.*'],
      insertTypesEntry: true,
    }),
    preserveDirectives(),
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  build: {
    lib: {
      entry: resolve(__dirname, 'src/main.ts'),
      name: 'main',
      formats: ['es'],
      fileName: 'main',
    },
    rollupOptions: {
      external: [...Object.keys(peerDependencies)],
      output: {
        banner: '"use client";',
        globals: {
          react: 'React',
          'react/jsx-runtime': 'react/jsx-runtime',
          'react-dom': 'ReactDOM',
          tailwindcss: 'tailwindcss',
        },
      },
    },
    target: 'esnext',
    sourcemap: true,
  },
});

global.css

@import 'tailwindcss';

/* we tried with :root, also didn't work */
@theme {
  /* shortned here to not paste everything */
  --brand-orange-900: hsla(38, 96%, 45%, 1);
  --brand-orange-100: hsla(38, 90%, 85%, 1);
}

package.json exports (from the component library):

"type": "module",
"main": "dist/main.js",
"types": "dist/main.d.ts",
"files": [
  "dist"
],
"exports": {
  "./global.css": "./src/global.css"
},

Solution

  • In a CSS-first configuration, the --color prefix/namespace should be used to declare colors:

    <script src="https://unpkg.com/@tailwindcss/browser@4"></script>
    <style type="text/tailwindcss">
    @theme {
      --color-brand-orange-900: hsla(38, 96%, 45%, 1);
      --color-brand-orange-500: hsla(38, 93%, 50%, 1);
      --color-brand-orange-100: hsla(38, 90%, 85%, 1);
    }
    </style>
    
    <input
      class="
        bg-brand-orange-900 hover:bg-brand-orange-100/50 focus:bg-brand-orange-100
        text-brand-orange-100 hover:text-brand-orange-900/50 focus:text-brand-orange-500
        p-4
      "
      value="Example Text"
    >

    Namespace Utility classes
    --color-* Color utilities like bg-red-500, text-sky-300, and many more