CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vite-plugin-css-injected-by-js

A Vite plugin that injects CSS into JavaScript bundles for single-file applications.

Pending
Overview
Eval results
Files

development-mode.mddocs/

Development Mode

Experimental development server integration with hot-reload support for CSS injection during development.

Capabilities

Development Options

Configure experimental development mode with CSS hot-reload support.

/**
 * Development mode configuration (experimental)
 */
interface DevOptions {
  /** Enable plugin in development server */
  enableDev?: boolean;
  /** Custom style removal code for hot-reload */
  removeStyleCode?: (id: string) => string;
  /** Custom style removal runtime function for hot-reload */
  removeStyleCodeFunction?: (id: string) => void;
}

Usage Examples:

import { defineConfig } from "vite";
import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";

// Basic development mode
export default defineConfig({
  plugins: [
    cssInjectedByJsPlugin({
      dev: {
        enableDev: true,
      },
    }),
  ],
});

// Development mode with custom style removal
export default defineConfig({
  plugins: [
    cssInjectedByJsPlugin({
      dev: {
        enableDev: true,
        removeStyleCodeFunction: (id) => {
          console.log(`Removing styles for: ${id}`);
          // Custom cleanup logic
        },
      },
    }),
  ],
});

Enable Development Mode

Activate plugin functionality in Vite's development server.

/**
 * Enable plugin in development server
 * WARNING: Experimental feature with non-conventional implementation
 */
enableDev?: boolean;

Usage Examples:

// Enable development mode
dev: {
  enableDev: true
}

Important Notes:

  • This is an experimental feature using non-conventional solutions
  • Development mode modifies CSS import behavior to inject styles via JavaScript
  • Hot-reload functionality requires proper style removal code

Custom Style Removal Code

Provide custom JavaScript code for removing injected styles during hot-reload.

/**
 * Custom style removal code for hot-reload
 * @param id - Vite development ID for the CSS file
 * @returns JavaScript code string that removes the injected styles
 */
removeStyleCode?: (id: string) => string;

Usage Examples:

// Custom removal code
removeStyleCode: (id) => `
  {
    const elements = document.querySelectorAll('style[data-vite-dev-id="${id}"]');
    elements.forEach(el => el.remove());
  }
`

// Enhanced removal with logging
removeStyleCode: (id) => `
  {
    console.log('Removing styles for:', '${id}');
    const selector = 'style[data-vite-dev-id="${id}"]';
    const elements = document.querySelectorAll(selector);
    elements.forEach(element => {
      element.remove();
    });
  }
`

Custom Style Removal Function

Provide a runtime function for removing injected styles during hot-reload.

/**
 * Custom style removal runtime function for hot-reload
 * @param id - Vite development ID for the CSS file
 */
removeStyleCodeFunction?: (id: string) => void;

Usage Examples:

// Simple removal function
removeStyleCodeFunction: (id) => {
  const elements = document.querySelectorAll(`style[data-vite-dev-id="${id}"]`);
  elements.forEach(el => el.remove());
}

// Enhanced removal with error handling
removeStyleCodeFunction: (id) => {
  try {
    const selector = `style[data-vite-dev-id="${id}"]`;
    const elements = document.querySelectorAll(selector);
    console.log(`Removing ${elements.length} style elements for ${id}`);
    elements.forEach(element => {
      element.remove();
    });
  } catch (error) {
    console.warn('Failed to remove styles:', error);
  }
}

Development Mode Implementation Details

How Development Mode Works

  1. CSS Import Transformation: The plugin intercepts CSS imports during development
  2. Style Injection: CSS is injected via JavaScript instead of being served as separate files
  3. Hot-Reload Support: Styles are removed and re-injected when CSS files change
  4. Attribute Tracking: Injected styles include data-vite-dev-id attributes for identification

Style Element Attributes in Development

During development, injected style elements include additional attributes:

interface DevModeAttributes {
  "data-vite-dev-id": string; // Vite's development file ID
  [key: string]: string; // Additional custom attributes
}

Compatibility with Custom Injection

When using custom injection functions (injectCode or injectCodeFunction) in development mode:

  • The options.attributes object includes the data-vite-dev-id attribute
  • Custom injection functions must handle the development attributes appropriately
  • Style removal functions must target styles with the correct data-vite-dev-id value

Example with custom injection and development mode:

export default defineConfig({
  plugins: [
    cssInjectedByJsPlugin({
      dev: {
        enableDev: true,
        removeStyleCodeFunction: (id) => {
          // Remove styles using the dev ID
          const elements = document.querySelectorAll(`style[data-vite-dev-id="${id}"]`);
          elements.forEach(el => el.remove());
        },
      },
      injectCodeFunction: (cssCode, options) => {
        try {
          if (typeof document !== 'undefined') {
            const style = document.createElement('style');
            
            // Set all attributes including dev attributes
            for (const [key, value] of Object.entries(options.attributes || {})) {
              style.setAttribute(key, value);
            }
            
            style.appendChild(document.createTextNode(cssCode));
            document.head.appendChild(style);
          }
        } catch (error) {
          console.error('CSS injection failed:', error);
        }
      },
    }),
  ],
});

Development Mode Limitations

  • Experimental Status: May have unexpected behavior or breaking changes
  • Performance Impact: Additional JavaScript execution during development
  • Custom Injection Requirements: Must implement compatible style removal when using custom injection
  • Hot-Reload Dependencies: Requires proper cleanup for smooth hot-reload experience

Install with Tessl CLI

npx tessl i tessl/npm-vite-plugin-css-injected-by-js

docs

configuration.md

custom-injection.md

development-mode.md

index.md

tile.json