JSX AST Utilities X

0.1.0 · active · verified Sun Apr 19

jsx-ast-utils-x is a dedicated utility module for statically analyzing JSX Abstract Syntax Tree (AST) nodes. It provides a set of helper functions to query and extract information from JSX elements, attributes, and expressions, making it particularly useful for developing custom ESLint rules or other static analysis tools for React or similar JSX-based codebases. The current stable version is `0.1.0`. As a new package, its release cadence is likely to be agile, with minor versions addressing new features or bug fixes. Key differentiators include its focused scope, providing a core set of AST traversal and querying functions specifically for JSX, and its lean dependency tree (recently replacing external dependencies with built-in methods) which contributes to a smaller footprint and potentially better performance. It serves as a more modular and potentially more modern alternative to similar functionality found embedded in larger linting plugins.

Common errors

Warnings

Install

Imports

Quickstart

This ESLint rule example demonstrates how to use `hasProp`, `getPropValue`, and `elementType` to enforce accessibility best practices for JSX elements, specifically checking for `aria-label` attributes on elements and reporting issues for empty or missing labels on buttons.

import { hasProp, getPropValue, elementType } from 'jsx-ast-utils-x';

// Example ESLint rule integration
module.exports = {
  meta: {
    type: 'suggestion',
    schema: [],
  },
  create(context) {
    return {
      JSXOpeningElement(node) {
        // Check if the element has an 'aria-label' attribute
        const ariaLabelProp = hasProp(node.attributes, 'aria-label');
        if (ariaLabelProp) {
          const value = getPropValue(ariaLabelProp);
          if (typeof value === 'string' && value.trim() === '') {
            context.report({
              node,
              message: `Empty aria-label found on <${elementType(node)}> element.`,
            });
          }
        } else {
          // Report if a button doesn't have an aria-label or text content
          if (elementType(node) === 'button') {
            // In a real scenario, you'd also check children for text content
            context.report({
              node,
              message: 'Button elements should have an accessible label via `aria-label` or text content.',
            });
          }
        }
      },
    };
  },
};

view raw JSON →