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
Maintainers
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-idanddata-ct-nameattributes 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 -DBasic 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 testDistribution
The plugin is built using Rollup and supports multiple output formats:
- CommonJS:
dist/index.jsfor Node.js compatibility - ES Modules:
dist/index.mjsfor modern bundlers - TypeScript:
dist/index.d.tsfor type definitions
License
MIT © RonNakamoto
Built with ❤️ for the React community
