Registry / testing / jsx-ast-utils

jsx-ast-utils

JSON →
library3.3.5jsnpmunverified

jsx-ast-utils is a dedicated utility module designed for the static analysis of JSX Abstract Syntax Tree (AST) nodes. It provides functions to query, validate, and extract information from JSX elements, particularly focusing on prop existence and values. Currently stable at version 3.3.5, it offers a consistent API for working with JSX ASTs, making it an invaluable tool for authors of linting rules, code transformers, or other static analysis tools. Originally extracted from eslint-plugin-jsx-a11y, its primary differentiator is its focused scope on JSX syntax, providing robust and tested utilities that account for various JSX complexities including spread attributes and case insensitivity.

npm install jsx-ast-utils
INSTALL
IMPORT
SIG · JSX-AST-UTILS
J
jsx-ast-utils
testingjavascriptv3.3.5
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

hasProp
import { hasProp } from 'jsx-ast-utils';
const hasProp = require('jsx-ast-utils'); // Missing .hasProp after require
Primary ESM named import for checking prop existence. For CommonJS, use `const { hasProp } = require('jsx-ast-utils');`
getProp
import { getProp } from 'jsx-ast-utils';
const getProp = require('jsx-ast-utils/getProp'); // Direct file imports are discouraged and may break
Retrieves the full JSXAttribute node or `undefined`. Use named import for both ESM and CommonJS.
hasAnyProp
import { hasAnyProp } from 'jsx-ast-utils';
import hasAnyProp from 'jsx-ast-utils'; // No default export from the main package
Checks if any of the provided props exist on a JSX element. Always use named imports for top-level utilities.

Demonstrates how to use `hasProp` within a simplified ESLint-like visitor function to check for prop existence on JSX elements, including handling spread attributes and case insensitivity.

import { hasProp } from 'jsx-ast-utils'; // This example mimics an ESLint rule structure to demonstrate usage. // In a real ESLint rule, `context` and `node` would be provided by ESLint. const mockContext = { report: ({ node, message }) => console.log(`Report at node ${node.type}: ${message}`) }; const mockJSXOpeningElementNode = { type: 'JSXOpeningElement', attributes: [ { type: 'JSXAttribute', name: { type: 'JSXIdentifier', name: 'id' }, value: null }, { type: 'JSXAttribute', name: { type: 'JSXIdentifier', name: 'className' }, value: null }, { type: 'JSXSpreadAttribute', argument: { type: 'Identifier', name: 'props' } } ] }; // Example usage within a mock ESLint rule visitor function JSXOpeningElementVisitor(node, context) { const hasIdProp = hasProp(node.attributes, 'id'); const hasOnChange = hasProp(node.attributes, 'onChange', { spreadStrict: false }); // Look within spreads const hasDataAttr = hasProp(node.attributes, 'data-testId', { ignoreCase: true }); // Case-insensitive search if (!hasIdProp) { context.report({ node, message: `JSX element is missing 'id' prop.` }); } if (hasOnChange) { context.report({ node, message: `JSX element has an 'onChange' prop, which might be a concern.` }); } if (hasDataAttr) { context.report({ node, message: `JSX element has a data-testid attribute.` }); } } // Simulate ESLint calling the visitor JSXOpeningElementVisitor(mockJSXOpeningElementNode, mockContext);
Debug
Known issues
breakingIn `v2.0.0`, the internal `propName` utility (and consequently functions like `getProp`) was changed to always return a value, where previously it might have returned `undefined` or thrown an error for certain cases. If your code relied on this previous behavior, it constitutes a breaking change.
fix
Review any code that interacts with `getProp` or related utilities to ensure it correctly handles the guaranteed return of a value, even if the prop is not found or malformed. Adjust checks from `if (!prop)` to `if (prop === undefined)` if strict non-existence handling is needed.
affects: >=2.0.0
gotchaThe `hasProp`, `hasAnyProp`, and `hasEveryProp` utilities default `spreadStrict` to `true`. This means if a prop is supplied via a JSX spread attribute (`{...props}`), the utility will report that the specific prop does NOT exist.
fix
To correctly check for props that might be included through spread attributes, explicitly set `spreadStrict: false` in the options object: `hasProp(attributes, 'myProp', { spreadStrict: false })`.
affects: >=1.0.0
gotchaThe `hasProp`, `hasAnyProp`, and `hasEveryProp` utilities default `ignoreCase` to `true`. This means they will find a prop like 'onClick' if you search for 'onclick'.
fix
If strict case-sensitive matching is required for a prop, you must implement a manual check. This can involve iterating through the `node.attributes` array and performing a case-sensitive comparison on `attribute.name.name`.
affects: >=1.0.0
breakingSupport for TypeScript AST node types was officially added in `v2.1.0`. Older versions might not correctly parse or analyze TSX/TypeScript-specific AST nodes, leading to incorrect results or runtime errors when processing TypeScript codebases.
fix
Upgrade to `jsx-ast-utils@^2.1.0` or newer if working with TypeScript or TSX files to ensure proper AST node handling and prevent unexpected behavior.
affects: <2.1.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'attributes')
This error occurs when attempting to access the `attributes` property on an AST node that is not a `JSXOpeningElement`. The `attributes` property is specific to JSX opening tags.
fix
Before accessing `node.attributes` or passing a node to `jsx-ast-utils` functions expecting JSX attributes, ensure that `node.type === 'JSXOpeningElement'` (or a similar check for relevant JSX node types).
ReferenceError: require is not defined in ES module scope
This typically happens when you are using CommonJS `require()` syntax within an ECMAScript module (ESM) environment (e.g., in a Node.js project with `"type": "module"` in `package.json` or in a modern browser context).
fix
Switch to ESM import syntax: `import { hasProp } from 'jsx-ast-utils';` for named exports.
TypeError: hasProp is not a function
This error often indicates an incorrect import or destructuring when using CommonJS. Common mistakes include `require('jsx-ast-utils')` without subsequently accessing `.hasProp`, or attempting `require('jsx-ast-utils/hasProp')` assuming a default export from a subpath.
fix
For CommonJS, ensure you are correctly destructuring the named export: `const { hasProp } = require('jsx-ast-utils');`.
Upgrade
Version history
3.3.5latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources