npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

vite-plugin-component-instrumentation

v1.1.1

Published

A professional Vite plugin that automatically adds identifying data attributes to React components for debugging, testing, and analytics

Readme

vite-plugin-component-instrumentation

A professional-grade Vite plugin that provides comprehensive React component instrumentation for debugging, testing, analytics, and observability in production applications.

Overview

This plugin automatically instruments React components by adding identifying data attributes and optional runtime state tracking. It's designed for enterprise applications requiring component-level observability, reliable testing selectors, and debugging capabilities.

Key Features

  • Automatic Component Instrumentation: Adds data-ct-id and data-ct-name attributes to all React components
  • Runtime State Tracking: Optional real-time component state monitoring with security filtering
  • Enterprise Security: Built-in sensitive data protection and configurable allowlists
  • Performance Optimized: Minimal build and runtime impact with intelligent throttling
  • TypeScript Support: Full type safety with comprehensive type definitions
  • Production Ready: Configurable production build enablement
  • Source Map Support: Maintains debugging capabilities across transformations
  • Zero Dependencies: Only essential runtime dependencies included

Installation

npm install vite-plugin-component-instrumentation --save-dev
# or
yarn add vite-plugin-component-instrumentation -D
# or
pnpm add vite-plugin-component-instrumentation -D

Basic Configuration

Add the plugin to your vite.config.ts:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import componentInstrumentation from 'vite-plugin-component-instrumentation';

export default defineConfig({
  plugins: [
    react(),
    componentInstrumentation()
  ],
});

Advanced Configuration

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import componentInstrumentation from 'vite-plugin-component-instrumentation';

export default defineConfig({
  plugins: [
    react(),
    componentInstrumentation({
      // Customize attribute prefix (default: 'data-ct')
      attributePrefix: 'data-debug',

      // File extensions to process (default: ['.jsx', '.tsx'])
      extensions: ['.jsx', '.tsx', '.js', '.ts'],

      // Enable in production builds (default: false)
      enableInProduction: false,

      // Patterns to exclude (default: ['node_modules'])
      excludePatterns: ['node_modules', 'dist', 'build'],

      // Include tag names in attributes (default: true)
      includeTagName: true,

      // Custom ID generator function
      customIdGenerator: (file, loc) => `${file}#L${loc.line}:C${loc.column}`,

      // Enable debug logging (default: false)
      debug: true,

      // Runtime state tracking mode
      trackState: 'summary', // 'off' | 'events' | 'summary'

      // Security: explicitly allowed state keys
      allowKeys: ['count', 'formData', 'name', 'email'],

      // Maximum attribute length for state summaries (default: 160)
      maxAttrLength: 300,

      // Throttle interval for runtime updates in ms (default: 120)
      throttleMs: 120,

      // Show full object contents in development (default: false)
      showFullObjects: true
    })
  ],
});

What It Does

The plugin automatically transforms your React components by adding instrumentation attributes:

Before Transformation

function MyComponent() {
  return (
    <div className="container">
      <button onClick={handleClick}>
        Click me
      </button>
    </div>
  );
}

After Transformation

function MyComponent() {
  return (
    <div data-ct-id="src/MyComponent.tsx:3:4" data-ct-name="div" className="container">
      <button data-ct-id="src/MyComponent.tsx:4:6" data-ct-name="button" onClick={handleClick}>
        Click me
      </button>
    </div>
  );
}

Configuration Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | attributePrefix | string | 'data-ct' | Prefix for data attributes | | extensions | string[] | ['.jsx', '.tsx'] | File extensions to process | | enableInProduction | boolean | false | Whether to enable in production builds | | excludePatterns | string[] | ['node_modules'] | Patterns to exclude from processing | | includeTagName | boolean | true | Whether to include tag name in attributes | | customIdGenerator | function | undefined | Custom ID generator function | | debug | boolean | false | Enable debug logging | | trackState | 'off' \| 'events' \| 'summary' | 'off' | Runtime state tracking mode | | allowKeys | string[] | [] | Explicitly allowed state keys for security | | maxAttrLength | number | 160 | Maximum attribute length for state summaries | | throttleMs | number | 120 | Throttle interval for runtime updates | | showFullObjects | boolean | false | Show full object contents in development |

Use Cases

Automated Testing

Use the generated attributes as reliable test selectors:

// Jest/Testing Library
const button = screen.getByTestId('data-ct-name', 'button');

// Cypress
cy.get('[data-ct-name="button"]').click();

// Playwright
await page.click('[data-ct-name="button"]');

Analytics & User Behavior Tracking

Track component interactions for analytics:

document.addEventListener('click', (event) => {
  const componentId = event.target.getAttribute('data-ct-id');
  const componentName = event.target.getAttribute('data-ct-name');

  analytics.track('component_interaction', {
    id: componentId,
    name: componentName,
    timestamp: Date.now()
  });
});

Development Tools & Debugging

Build development tools that understand your component structure:

// Find all components of a specific type
const buttons = document.querySelectorAll('[data-ct-name="button"]');

// Get component source location for debugging
const sourceLocation = element.getAttribute('data-ct-id');

// Runtime state inspection (when trackState is enabled)
const componentState = element.getAttribute('data-ct-state');

Production Monitoring

Monitor component performance and errors in production:

// Error boundary with component context
window.addEventListener('error', (event) => {
  const componentId = event.target?.closest('[data-ct-id]')?.getAttribute('data-ct-id');
  
  errorReporting.captureException(event.error, {
    tags: { componentId },
    extra: { componentLocation: componentId }
  });
});

Security Features

The plugin includes enterprise-grade security features:

  • Automatic Sensitive Data Filtering: Prevents exposure of passwords, tokens, and personal information
  • Configurable Allowlists: Explicit control over which state keys are exposed
  • Redacted Summaries: Safe state representation without exposing sensitive values
  • Production Controls: Optional production build enablement

Performance

  • Minimal Build Impact: Efficient AST parsing with Magic String transformations
  • Runtime Optimization: Throttled updates and intelligent batching
  • Memory Efficient: WeakMap-based caching and cleanup
  • Zero Bundle Bloat: Only essential runtime code included when needed

Examples

Check out the /examples directory for complete working examples:

  • Basic: Simple setup with default configuration
  • Advanced: Custom configuration with TypeScript and state tracking

Development

# Clone the repository
git clone https://github.com/ronnakamoto/vite-plugin-component-instrumentation.git
cd vite-plugin-component-instrumentation

# Install dependencies
npm install

# Build the plugin
npm run build

# Run tests
npm test

Distribution

The plugin is built using Rollup and supports multiple output formats:

  • CommonJS: dist/index.js for Node.js compatibility
  • ES Modules: dist/index.mjs for modern bundlers
  • TypeScript: dist/index.d.ts for type definitions

License

MIT © RonNakamoto

Built with ❤️ for the React community