Webpack plugin that adds location data to JSX elements
A Webpack plugin that adds data-loc attributes to JSX elements, containing the file path and line number where the element is defined. This is useful for debugging, component tracking, and analytics.
``bash`
npm install --save-dev webpack-plugin-jsx-locor
yarn add --dev webpack-plugin-jsx-loc
Add the plugin to your Webpack configuration:
`js
// webpack.config.js
const { JsxLocPlugin } = require('@builder.io/webpack-plugin-jsx-loc');
module.exports = {
// ... other webpack config
plugins: [
new JsxLocPlugin({
// Optional: specify custom include/exclude patterns
// include: [/src\/components/],
// exclude: [/node_modules/, /test/]
})
]
};
`
- include: RegExp or array of RegExp patterns to include specific files (optional)exclude
- : RegExp or array of RegExp patterns to exclude specific files (optional, defaults to /node_modules/)
The plugin adds a data-loc attribute to JSX elements that contains the relative file path and line number:
`jsx
// Input
// Output
`
This allows you to identify where components are defined when inspecting the DOM.
The plugin handles a variety of JSX patterns:
- Regular JSX elements with attributes
- Member expressions (e.g., )
- Namespaced elements (e.g., )
- JSX inside decorators and complex class components
- Components with TypeScript interfaces and typing
- CSS-in-JS libraries (emotion, styled-components)
- Components with spread attributes
React Fragments are intentionally skipped and won't receive a data-loc attribute:
- elements<>
- Shorthand fragment syntax
- elements
This package includes comprehensive tests and manual testing scripts:
`bashRun the automated tests
npm test
Tests are powered by Vitest, a fast test runner built on top of Vite.
The test suite uses real fixtures to verify the plugin's behavior with a variety of components:
- Simple components
- Components with fragments
- Complex components with decorators and nested JSX
- Components using CSS-in-JS libraries
- Components with TypeScript interfaces and typing
- Real-world complex components with hundreds of lines of code and multiple levels of nesting
Both unit tests and integration tests ensure that the plugin correctly adds
data-loc attributes even to highly complex components with nested structures, decorators, CSS-in-JS properties, and other challenging patterns.Tests include both assertions and inline snapshots that precisely verify the transformation output to catch any regressions or unexpected changes in how JSX is processed.
The test scripts generate output in
src/__tests__/output/ where you can inspect the transformation results.Notes
- Only works with
.jsx and .tsx` files