Node.js-specific utilities and runtime functionality for Tailwind CSS v4, providing compilation tools, module dependency analysis, source map handling, path normalization, and optimization utilities.
Node.js module cache management for hot module reloading and development workflows. Provides utilities to clear specific files from Node.js require cache and ESM module cache busting for development environments.
Clears specific files from the Node.js require cache for hot module reloading.
/**
* Clears specific files from Node.js require cache
* Useful for hot module reloading in development environments
* @param files - Array of absolute file paths to remove from cache
*/
function clearRequireCache(files: string[]): void;Usage Examples:
import { clearRequireCache } from "@tailwindcss/node/require-cache";
// Clear specific files from cache
const filesToClear = [
"/path/to/project/src/config.js",
"/path/to/project/src/utils.js"
];
clearRequireCache(filesToClear);
// Now requiring these files will reload them from disk
const config = require("/path/to/project/src/config.js"); // Fresh loadIntegration with file watchers for automatic cache clearing:
import { clearRequireCache } from "@tailwindcss/node/require-cache";
import { watch } from "chokidar";
import path from "path";
// Set up hot module reloading for a project
function setupHMR(watchPaths: string[]) {
const watcher = watch(watchPaths, {
ignoreInitial: true
});
watcher.on('change', (changedFile) => {
const absolutePath = path.resolve(changedFile);
console.log(`File changed: ${absolutePath}`);
// Clear from require cache
clearRequireCache([absolutePath]);
// Also clear any files that depend on this file
const dependentFiles = findDependentFiles(absolutePath);
if (dependentFiles.length > 0) {
clearRequireCache(dependentFiles);
console.log(`Cleared dependent files:`, dependentFiles);
}
// Trigger rebuild
rebuild();
});
return watcher;
}
// Usage
const watcher = setupHMR([
"src/**/*.js",
"config/**/*.js",
"tailwind.config.js"
]);Use with development servers for automatic reloading:
import { clearRequireCache } from "@tailwindcss/node/require-cache";
import express from "express";
const app = express();
// Middleware to clear cache on development requests
app.use('/api/reload', (req, res) => {
const { files } = req.body;
if (Array.isArray(files)) {
clearRequireCache(files.map(file => path.resolve(file)));
res.json({ success: true, cleared: files.length });
} else {
res.status(400).json({ error: "Files array required" });
}
});
// Development route that always uses fresh modules
app.get('/api/config', (req, res) => {
const configPath = path.resolve('./config.js');
// Clear cache to ensure fresh config
clearRequireCache([configPath]);
// Require fresh config
delete require.cache[configPath]; // Alternative approach
const config = require(configPath);
res.json(config);
});Integration with build tools for cache management:
import { clearRequireCache } from "@tailwindcss/node/require-cache";
// Webpack plugin example
class CacheClearPlugin {
constructor(private patterns: string[]) {}
apply(compiler: any) {
compiler.hooks.watchRun.tap('CacheClearPlugin', () => {
// Clear cache for specific patterns on rebuild
const filesToClear = this.patterns.flatMap(pattern =>
glob.sync(pattern).map(file => path.resolve(file))
);
if (filesToClear.length > 0) {
clearRequireCache(filesToClear);
console.log(`Cleared ${filesToClear.length} files from require cache`);
}
});
}
}
// Usage in webpack config
module.exports = {
plugins: [
new CacheClearPlugin([
'src/config/**/*.js',
'tailwind.config.js'
])
]
};Implement configuration hot reloading for development:
import { clearRequireCache } from "@tailwindcss/node/require-cache";
import fs from "fs";
class ConfigManager {
private configPath: string;
private config: any;
private watchers: Set<() => void> = new Set();
constructor(configPath: string) {
this.configPath = path.resolve(configPath);
this.loadConfig();
this.watchConfig();
}
private loadConfig() {
// Clear cache to ensure fresh load
clearRequireCache([this.configPath]);
try {
this.config = require(this.configPath);
console.log('Config loaded:', this.configPath);
} catch (error) {
console.error('Failed to load config:', error);
this.config = {};
}
}
private watchConfig() {
fs.watchFile(this.configPath, () => {
console.log('Config file changed, reloading...');
this.loadConfig();
// Notify watchers
this.watchers.forEach(callback => callback());
});
}
getConfig() {
return this.config;
}
onConfigChange(callback: () => void) {
this.watchers.add(callback);
return () => this.watchers.delete(callback);
}
}
// Usage
const configManager = new ConfigManager('./app.config.js');
const unwatch = configManager.onConfigChange(() => {
console.log('Config updated:', configManager.getConfig());
// Restart services, update app state, etc.
});The package also provides ESM cache busting through the ESM cache loader:
// ESM cache loader is automatically registered when importing @tailwindcss/node
import "@tailwindcss/node"; // Registers ESM cache loader
// The loader adds cache-busting IDs to ESM imports
// import('./module.js') becomes import('./module.js?id=1234567890')// For custom ESM cache busting (advanced usage)
import { pathToFileURL } from "url";
import { register } from "node:module";
// Register custom ESM loader
register(pathToFileURL('./custom-esm-loader.mjs'));
// In custom-esm-loader.mjs:
export async function resolve(specifier, context, nextResolve) {
const result = await nextResolve(specifier, context);
// Add cache busting parameter
if (shouldBustCache(result.url)) {
const url = new URL(result.url);
url.searchParams.set('cache-bust', Date.now().toString());
return { ...result, url: url.toString() };
}
return result;
}import { clearRequireCache } from "@tailwindcss/node/require-cache";
// Clear only related files instead of entire cache
function clearRelatedFiles(changedFile: string) {
const relatedFiles = findRelatedFiles(changedFile);
clearRequireCache(relatedFiles);
}
function findRelatedFiles(changedFile: string): string[] {
// Implementation depends on your dependency graph
// Example: clear config files when source files change
if (changedFile.includes('/src/')) {
return [
path.resolve('./tailwind.config.js'),
path.resolve('./app.config.js')
];
}
return [changedFile];
}import { clearRequireCache } from "@tailwindcss/node/require-cache";
// Track cache clearing statistics
class CacheManager {
private clearCount = 0;
private clearedFiles = new Set<string>();
clearCache(files: string[]) {
clearRequireCache(files);
this.clearCount++;
files.forEach(file => this.clearedFiles.add(file));
console.log(`Cache clear #${this.clearCount}: ${files.length} files`);
}
getStatistics() {
return {
totalClears: this.clearCount,
uniqueFilesCleared: this.clearedFiles.size,
currentCacheSize: Object.keys(require.cache).length
};
}
}
const cacheManager = new CacheManager();import { clearRequireCache } from "@tailwindcss/node/require-cache";
// Prevent memory leaks in long-running processes
function periodicCacheCleanup() {
const maxCacheSize = 1000;
const currentCacheSize = Object.keys(require.cache).length;
if (currentCacheSize > maxCacheSize) {
// Clear non-core modules
const nonCoreModules = Object.keys(require.cache)
.filter(key => !key.includes('node_modules'))
.slice(0, Math.floor(maxCacheSize * 0.5));
clearRequireCache(nonCoreModules);
console.log(`Cleared ${nonCoreModules.length} modules from cache`);
}
}
// Run cleanup every 10 minutes in development
if (process.env.NODE_ENV === 'development') {
setInterval(periodicCacheCleanup, 10 * 60 * 1000);
}// The package detects Bun and skips ESM registration
if (process.versions.bun) {
// ESM modules populate require.cache in Bun
// so cache clearing works the same way
clearRequireCache(files);
} else {
// Node.js requires ESM cache loader registration
// This is handled automatically by @tailwindcss/node
}// Module.register() was added in Node v18.19.0 and v20.6.0
if (typeof Module.register === 'function') {
// Modern Node.js with ESM loader support
Module.register(loaderPath);
} else {
// Older Node.js versions - fallback to require cache only
console.warn('ESM cache busting not available in this Node.js version');
}clearRequireCache()tessl i tessl/npm-tailwindcss--node@4.1.0docs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10