JSX AST Utilities

3.3.5 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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);

view raw JSON →