CtrlK
CommunityDocumentationLog inGet started
Tessl Logo

tessl/npm-tailwindcss--node

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.

43%

Overall

Evaluation43%

1.16x

Agent success when using this tile

Overview
Eval results
Files

cache-management.mddocs/

Cache Management

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.

Capabilities

Clear Require Cache Function

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 load

Hot Module Reloading Setup

Integration 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"
]);

Development Server Integration

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);
});

Build Tool Integration

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'
    ])
  ]
};

Configuration Reloading

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.
});

ESM Cache Busting

The package also provides ESM cache busting through the ESM cache loader:

ESM Module Registration

// 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')

Custom ESM Cache Implementation

// 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;
}

Performance Considerations

Selective Cache Clearing

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];
}

Cache Statistics

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();

Memory Management

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);
}

Platform Considerations

Bun Compatibility

// 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
}

Node.js Version Compatibility

// 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');
}

Best Practices

  1. Clear Related Files: When clearing cache, also clear dependent modules
  2. Use Absolute Paths: Always use absolute paths with clearRequireCache()
  3. Selective Clearing: Clear only necessary files to avoid performance issues
  4. Development Only: Avoid cache clearing in production environments
  5. Error Handling: Wrap cache operations in try-catch blocks
  6. Memory Monitoring: Monitor cache size in long-running processes
tessl i tessl/npm-tailwindcss--node@4.1.0

docs

cache-management.md

compilation.md

index.md

instrumentation.md

module-analysis.md

optimization.md

path-utils.md

source-maps.md

url-processing.md

tile.json