tw4-webworker
v0.1.1
Published
A web worker-based Tailwind CSS compiler for browser environments
Maintainers
Readme
tw4-webworker
A web worker-based Tailwind CSS compiler for browser environments. Compile Tailwind CSS classes on-demand in the browser without Node.js dependencies.
Features
- 🚀 Browser-native - No Node.js required, works in any modern browser
- ⚡ Web Worker powered - Non-blocking compilation using Web Workers
- 🎯 On-demand compilation - Only compile the classes you actually use
- 📦 Small footprint - Optimized bundles with tree-shaking support
- 🔧 TypeScript ready - Full TypeScript support with comprehensive type definitions
- 🎨 Layer extraction - Extract specific CSS layers (utilities, components, base)
Installation
npm install tw4-webworker
# or
yarn add tw4-webworker
# or
pnpm add tw4-webworkerQuick Start
import TailwindCompiler from 'tw4-webworker';
const compiler = new TailwindCompiler();
// Compile some Tailwind classes
const css = await compiler.compile({
classes: ['bg-blue-500', 'text-white', 'p-4', 'rounded-lg']
});
console.log(css);
// Output: CSS string with the compiled stylesAPI Reference
Constructor
const compiler = new TailwindCompiler(config?);Parameters:
config(optional) - Configuration options for the compiler
Methods
compile(options)
Compiles Tailwind CSS classes and returns a Promise with the generated CSS.
const css = await compiler.compile({
classes: ['bg-red-500', 'hover:bg-red-600'],
css: '@tailwind base; @tailwind components; @tailwind utilities;',
extract: 'utilities'
});Options:
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| classes | string[] | [] | Array of Tailwind class names to compile |
| css | string | '' | Optional custom CSS/theme to include |
| extract | string \| object | null | Extract specific CSS layer |
Extract Options:
'utilities'- Extract only utility classes'components'- Extract only component classes'base'- Extract only base styles{ layer: 'custom-layer' }- Extract a custom layer
Layer Extraction Methods
// Extract specific layers from compiled CSS
const utilities = compiler.extractUtilities(cssString);
const components = compiler.extractComponents(cssString);
const base = compiler.extractBase(cssString);
const custom = compiler.extractLayer(cssString, 'my-layer');Usage Examples
Basic Usage
import TailwindCompiler from 'tw4-webworker';
const compiler = new TailwindCompiler();
// Simple compilation
const css = await compiler.compile({
classes: ['flex', 'items-center', 'justify-between', 'p-6']
});
// Apply to element
document.head.insertAdjacentHTML('beforeend', `<style>${css}</style>`);With Custom CSS
const css = await compiler.compile({
classes: ['btn-primary', 'text-lg'],
css: `
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.btn-primary {
@apply bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600;
}
}
`
});Extract Specific Layers
// Only get utility classes
const utilities = await compiler.compile({
classes: ['bg-gray-100', 'p-4', 'rounded'],
extract: 'utilities'
});
// Only get component classes
const components = await compiler.compile({
classes: ['btn', 'card', 'nav'],
extract: 'components'
});
// Extract custom layer
const customLayer = await compiler.compile({
classes: ['my-component'],
extract: { layer: 'custom' }
});Dynamic Class Compilation
const compiler = new TailwindCompiler();
// Function to compile classes and apply them
async function applyClasses(element, classes) {
const css = await compiler.compile({ classes });
// Create or update style tag
let styleTag = document.getElementById('dynamic-tailwind');
if (!styleTag) {
styleTag = document.createElement('style');
styleTag.id = 'dynamic-tailwind';
document.head.appendChild(styleTag);
}
styleTag.textContent = css;
element.className = classes.join(' ');
}
// Usage
const button = document.querySelector('#my-button');
await applyClasses(button, ['bg-green-500', 'hover:bg-green-600', 'text-white', 'px-6', 'py-3']);TypeScript Usage
import TailwindCompiler, { CompileOptions, TailwindCompilerConfig } from 'tw4-webworker';
// Basic usage
const compiler = new TailwindCompiler();
// With configuration
const config: TailwindCompilerConfig = {
// Add any configuration options here
};
const configuredCompiler = new TailwindCompiler(config);
const options: CompileOptions = {
classes: ['bg-indigo-500', 'text-white'],
extract: 'utilities'
};
const css: string = await compiler.compile(options);Advanced Usage
Performance Optimization
The compiler uses a singleton Web Worker, so multiple instances share the same worker for optimal performance:
// All instances share the same worker
const compiler1 = new TailwindCompiler();
const compiler2 = new TailwindCompiler();
// Parallel compilation
const [css1, css2] = await Promise.all([
compiler1.compile({ classes: ['bg-red-500'] }),
compiler2.compile({ classes: ['bg-blue-500'] })
]);Error Handling
try {
const css = await compiler.compile({
classes: ['invalid-class', 'bg-green-500']
});
} catch (error) {
console.error('Compilation failed:', error.message);
}Browser Support
- Chrome 80+
- Firefox 78+
- Safari 13.1+
- Edge 80+
Requires support for:
- Web Workers
- ES6 Modules
- Async/Await
Bundle Sizes
| Format | Size | Gzipped | |--------|------|---------| | ES Module | ~2.6KB | ~0.9KB | | UMD | ~265KB | ~63KB | | Worker | ~264KB | ~63KB |
Note: The worker contains the full Tailwind CSS compiler and is loaded separately.
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Make your changes and add tests
- Run the build:
npm run build - Submit a pull request
License
MIT License - see LICENSE file for details.
Related Projects
- Tailwind CSS - The utility-first CSS framework
- Vite - Build tool used for bundling
Changelog
0.1.0
- Initial release
- Web Worker-based compilation
- TypeScript support
- Layer extraction functionality
- Multiple output formats (ES, UMD)
