Vite Plugin Scope Tailwind
raw JSON → 2.0.2 verified Mon Apr 27 auth: no javascript
A Vite plugin (v2.0.2, latest) that encapsulates and scopes TailwindCSS styles in library builds, preventing class name clashes with consumer apps. By appending unique IDs to Tailwind classes automatically (similar to Tailwind's prefix option but automatic), it avoids the need for manual prefixing or !important hacks. Supports React with the react option and allows ignoring specific classes via regex or strings. Actively maintained, ships TypeScript types.
Common errors
error Could not find a declaration file for module 'vite-plugin-scope-tailwind' ↓
cause Missing type declaration before v2.0.2.
fix
Upgrade to v2.0.2+ or manually add a
declare module 'vite-plugin-scope-tailwind' in a .d.ts file. error Error: PostCSS plugin tailwindcss requires tailwindcss to be configured ↓
cause TailwindCSS not installed or postcss.config.js missing.
fix
Run
npm install tailwindcss -D and create a postcss.config.js with module.exports = { plugins: { tailwindcss: {} } }. error Uncaught TypeError: scopeTailwind is not a function ↓
cause Using default import with CommonJS `require` incorrectly.
fix
Use
import scopeTailwind from 'vite-plugin-scope-tailwind' or const scopeTailwind = require('vite-plugin-scope-tailwind').default. Warnings
breaking v2.0.0 changed scoping mechanism from prefix-based to ID-append-based, breaking existing scoped class references. ↓
fix Upgrade to v2.0.0+ and verify that any hardcoded class references (e.g., in tests) are updated to match the new scoped format.
deprecated The `template` option was removed in v2.0.0; use `react` option instead. ↓
fix Replace `template: 'react'` with `react: true`.
gotcha Plugin must be placed before Tailwind's PostCSS plugin in the Vite config to avoid race conditions. ↓
fix Ensure scopeTailwind() is listed before any Tailwind-related PostCSS setup.
gotcha When using React, the plugin automatically handles JSX classes, but custom components may still leak styles. ↓
fix Wrap library components with a container class that is also scoped, or use the `ignore` option for specific classes.
Install
npm install vite-plugin-scope-tailwind yarn add vite-plugin-scope-tailwind pnpm add vite-plugin-scope-tailwind Imports
- scopeTailwind wrong
const scopeTailwind = require('vite-plugin-scope-tailwind')correctimport scopeTailwind from 'vite-plugin-scope-tailwind' - ScopeTailwindOptions wrong
import { ScopeTailwindOptions } from 'vite-plugin-scope-tailwind'correctimport type { ScopeTailwindOptions } from 'vite-plugin-scope-tailwind' - scopeTailwind (React usage) wrong
scopeTailwind({ react: 'true' })correctscopeTailwind({ react: true })
Quickstart
import scopeTailwind from 'vite-plugin-scope-tailwind';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
scopeTailwind({
react: false, // set to true if using React
ignore: [/^my-lib-/] // optional: ignore classes starting with 'my-lib-'
})
]
});