Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

jsx-ast-utils

jsx-eslint87.4mMIT3.3.5

AST utility module for statically analyzing JSX

jsx, ast, lint, eslint

readme

jsx-ast-utils [![Version Badge][npm-version-svg]][package-url]

github actions coverage [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] License Downloads

[![npm badge][npm-badge-png]][package-url]

AST utility module for statically analyzing JSX.

Installation

$ npm i jsx-ast-utils --save

Usage

This is a utility module to evaluate AST objects for JSX syntax. This can be super useful when writing linting rules for JSX code. It was originally in the code for eslint-plugin-jsx-a11y, however I thought it could be useful to be extracted and maintained separately so you could write new interesting rules to statically analyze JSX.

ESLint example

import { hasProp } from 'jsx-ast-utils';
// OR: var hasProp = require('jsx-ast-utils').hasProp;
// OR: const hasProp = require('jsx-ast-utils/hasProp');
// OR: import hasProp from 'jsx-ast-utils/hasProp';

module.exports = context => ({
  JSXOpeningElement: node => {
    const onChange = hasProp(node.attributes, 'onChange');

    if (onChange) {
      context.report({
        node,
        message: `No onChange!`
      });
    }
  }
});

API

AST Resources

  1. JSX spec
  2. JS spec

hasProp

hasProp(props, prop, options);

Returns boolean indicating whether an prop exists as an attribute on a JSX element node.

Props

Object - The attributes on the visited node. (Usually node.attributes).

Prop

String - A string representation of the prop you want to check for existence.

Options

Object - An object representing options for existence checking

  1. ignoreCase - automatically set to true.
  2. spreadStrict - automatically set to true. This means if spread operator exists in props, it will assume the prop you are looking for is not in the spread. Example: <div {...props} /> looking for specific prop here will return false if spreadStrict is true.

hasAnyProp

hasAnyProp(props, prop, options);

Returns a boolean indicating if any of props in prop argument exist on the node.

Props

Object - The attributes on the visited node. (Usually node.attributes).

Prop

Array<String> - An array of strings representing the props you want to check for existence.

Options

Object - An object representing options for existence checking

  1. ignoreCase - automatically set to true.
  2. spreadStrict - automatically set to true. This means if spread operator exists in props, it will assume the prop you are looking for is not in the spread. Example: <div {...props} /> looking for specific prop here will return false if spreadStrict is true.

hasEveryProp

hasEveryProp(props, prop, options);

Returns a boolean indicating if all of props in prop argument exist on the node.

Props

Object - The attributes on the visited node. (Usually node.attributes).

Prop

Array<String> - An array of strings representing the props you want to check for existence.

Options

Object - An object representing options for existence checking

  1. ignoreCase - automatically set to true.
  2. spreadStrict - automatically set to true. This means if spread operator exists in props, it will assume the prop you are looking for is not in the spread. Example: <div {...props} /> looking for specific prop here will return false if spreadStrict is true.

getProp

getProp(props, prop, options);

Returns the JSXAttribute itself or undefined, indicating the prop is not present on the JSXOpeningElement.

Props

Object - The attributes on the visited node. (Usually node.attributes).

Prop

String - A string representation of the prop you want to check for existence.

Options

Object - An object representing options for existence checking

  1. ignoreCase - automatically set to true.

elementType

elementType(node)

Returns the tagName associated with a JSXElement.

Node

Object - The visited JSXElement node object.


getPropValue

getPropValue(prop);

Returns the value of a given attribute. Different types of attributes have their associated values in different properties on the object.

This function should return the most closely associated value with the intention of the JSX.

Prop

Object - The JSXAttribute collected by AST parser.


getLiteralPropValue

getLiteralPropValue(prop);

Returns the value of a given attribute. Different types of attributes have their associated values in different properties on the object.

This function should return a value only if we can extract a literal value from its attribute (i.e. values that have generic types in JavaScript - strings, numbers, booleans, etc.)

Prop

Object - The JSXAttribute collected by AST parser.


propName

propName(prop);

Returns the name associated with a JSXAttribute. For example, given <div foo="bar" /> and the JSXAttribute for foo, this will return the string "foo".

Prop

Object - The JSXAttribute collected by AST parser.


eventHandlers

console.log(eventHandlers);
/*
[
  'onCopy',
  'onCut',
  'onPaste',
  'onCompositionEnd',
  'onCompositionStart',
  'onCompositionUpdate',
  'onKeyDown',
  'onKeyPress',
  'onKeyUp',
  'onFocus',
  'onBlur',
  'onChange',
  'onInput',
  'onSubmit',
  'onClick',
  'onContextMenu',
  'onDblClick',
  'onDoubleClick',
  'onDrag',
  'onDragEnd',
  'onDragEnter',
  'onDragExit',
  'onDragLeave',
  'onDragOver',
  'onDragStart',
  'onDrop',
  'onMouseDown',
  'onMouseEnter',
  'onMouseLeave',
  'onMouseMove',
  'onMouseOut',
  'onMouseOver',
  'onMouseUp',
  'onSelect',
  'onTouchCancel',
  'onTouchEnd',
  'onTouchMove',
  'onTouchStart',
  'onScroll',
  'onWheel',
  'onAbort',
  'onCanPlay',
  'onCanPlayThrough',
  'onDurationChange',
  'onEmptied',
  'onEncrypted',
  'onEnded',
  'onError',
  'onLoadedData',
  'onLoadedMetadata',
  'onLoadStart',
  'onPause',
  'onPlay',
  'onPlaying',
  'onProgress',
  'onRateChange',
  'onSeeked',
  'onSeeking',
  'onStalled',
  'onSuspend',
  'onTimeUpdate',
  'onVolumeChange',
  'onWaiting',
  'onLoad',
  'onError',
  'onAnimationStart',
  'onAnimationEnd',
  'onAnimationIteration',
  'onTransitionEnd',
]
*/

Contains a flat list of common event handler props used in JSX to attach behaviors to DOM events.

eventHandlersByType

The same list as eventHandlers, grouped into types.

console.log(eventHandlersByType);
/*
{
  clipboard: [ 'onCopy', 'onCut', 'onPaste' ],
  composition: [ 'onCompositionEnd', 'onCompositionStart', 'onCompositionUpdate' ],
  keyboard: [ 'onKeyDown', 'onKeyPress', 'onKeyUp' ],
  focus: [ 'onFocus', 'onBlur' ],
  form: [ 'onChange', 'onInput', 'onSubmit' ],
  mouse: [ 'onClick', 'onContextMenu', 'onDblClick', 'onDoubleClick', 'onDrag', 'onDragEnd', 'onDragEnter', 'onDragExit', 'onDragLeave', 'onDragOver', 'onDragStart', 'onDrop', 'onMouseDown', 'onMouseEnter', 'onMouseLeave', 'onMouseMove', 'onMouseOut', 'onMouseOver', 'onMouseUp' ],
  selection: [ 'onSelect' ],
  touch: [ 'onTouchCancel', 'onTouchEnd', 'onTouchMove', 'onTouchStart' ],
  ui: [ 'onScroll' ],
  wheel: [ 'onWheel' ],
  media: [ 'onAbort', 'onCanPlay', 'onCanPlayThrough', 'onDurationChange', 'onEmptied', 'onEncrypted', 'onEnded', 'onError', 'onLoadedData', 'onLoadedMetadata', 'onLoadStart', 'onPause', 'onPlay', 'onPlaying', 'onProgress', 'onRateChange', 'onSeeked', 'onSeeking', 'onStalled', 'onSuspend', 'onTimeUpdate', 'onVolumeChange', 'onWaiting' ],
  image: [ 'onLoad', 'onError' ],
  animation: [ 'onAnimationStart', 'onAnimationEnd', 'onAnimationIteration' ],
  transition: [ 'onTransitionEnd' ],
}
*/

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

v3.3.5 - 2023-07-28

Fixed

  • [Fix] extractProp: support JSXFragment #132

Commits

  • [Dev Deps] update @babel/core, @babel/eslint-parser, @babel/parser, eslint e5555d1
  • [Tests] fix a test bde3ba9

v3.3.4 - 2023-06-28

Commits

  • [Refactor] use array.prototype.flat object.values over .reduce bad51d0
  • [meta] add auto-changelog af1de69
  • [Tests] add test for import.meta 1d39f58
  • [Dev Deps] update @babel/core, @babel/eslint-parser, @babel/parser, aud, eslint, eslint-plugin-import 3baaf76
  • [Fix] TSNonNullExpression: Handle function calls 26cc3c4
  • [Dev Deps] update eslint, @babel/core, @babel/parser, object.entries, object.fromentries 0e4f80c
  • [Dev Deps] update @babel/core, @babel/eslint-parser, @babel/parser, aud b5427a6
  • [meta] run build in prepack, not prepublish a0f4f38
  • [Deps] update array-includes c479841
  • [Deps] update object.assign 9685dce

3.3.3 / 2022-08-08

  • [Fix] Mark ChainExpression as a noop (#109)
  • [Deps] update object.assign
  • [Dev Deps] update @babel/core, @babel/eslint-parser, @babel/parser, eslint

3.3.2 / 2022-07-06

  • [Fix] Handle as casts in TSNonNullExpression

3.3.1 / 2022-06-22

  • [Fix] ArrayExpression: handle sparse array (#117)
  • [Deps] update array-includes
  • [meta] move jest config to separate file
  • [meta] use npmignore to autogenerate an npmignore file
  • [Dev Deps] update @babel/core, @babel/eslint-parser, @babel/parser, eslint

3.3.0 / 2022-04-30

  • [New] add JSXFragment, JSXText; fix JSXElement to handle children
  • [Dev Deps] update @babel/core, @babel/parser, eslint, eslint-plugin-import

3.2.2 / 2022-03-31

  • [Fix] TSNonNullExpression: handle computed MemberExpressions (#109)
  • [Fix] avoid a crash in ChainExpressions in a TSAsExpression

3.2.1 / 2021-09-16

  • [patch] include project name in error logging (#113)
  • [readme] update badges, URLs
  • [Deps] update array-includes
  • [meta] don‘t lint coverage results
  • [meta] add GitHub org to FUNDING.yml
  • [meta] add OpenCollective to FUNDING.yml
  • [meta] run aud in posttest
  • [meta] add Automatic Rebase and Require Allow Edits workflows
  • [actions] use node/install instead of node/run; use codecov action
  • [Tests] unpin caniuse-lite, since breaking change is fixed
  • [Tests] pin caniuse-lite, due to breaking change in patch version
  • [Tests] fix linting errors
  • [Tests] migrate tests to Github Actions
  • [Tests] stop using coveralls
  • [Tests] skip failing fragment test in node 4
  • [Dev Deps] update @babel/core, @babel/parser, aud, eslint, eslint-plugin-import, object.entries, object.fromentries

3.2.0 / 2020-12-16

  • [New] add support for fragment syntax (<>) (#108)
  • [Fix] TSNonNullExpression: handle ThisExpressions (#108)
  • [Deps] update array-includes, object.assign
  • [Dev Deps] update @babel/core, @babel/parser, eslint, eslint-config-airbnb-base, object.entries, object.fromentries

3.1.0 / 2020-10-13

  • [New] add TSNonNullExpression (#105)
  • [New] add AssignmentExpression (#106)
  • [Dev Deps] update eslint

3.0.0 / 2020-10-06

  • [Breaking] Don't return node.start & node.end (#100)
  • [Breaking] add ChainExpression; CallExpression now includes arguments (#102)
  • [New] add SequenceExpression (#101)
  • [Deps] update object.assign
  • [Dev Deps] update eslint, eslint-plugin-import
  • [Dev Deps] update @babel/core, @babel/parser, eslint, eslint-plugin-import
  • [Tests] use proper actual, expected ordering for non-confusing failure messages

2.4.1 / 2020-06-11

  • [Fix] expressions/TemplateLiteral: use .range[0] instead of .start

2.4.0 / 2020-06-11

  • [New] Provide both range and start & end property on Node, support eslint v7 (#97)
  • [Dev Deps] update @babel/core, @babel/parser, eslint, eslint-config-airbnb-base, eslint-plugin-import, flow-parser
  • [meta] remove yarn registry from npmrc, so npm publish works

2.3.0 / 2020-05-24

  • [New] add nullish coalescing (#99)
  • [New] add OptionalCallExpression (#99)
  • [Deps] update array-includes
  • [meta] add safe-publish-latest
  • [Dev Deps] update @babel/parser, babel-eslint, coveralls, eslint, eslint-config-airbnb-base, eslint-plugin-import, in-publish, object.entries, object.fromentries, rimraf
  • [Tests] on node v14; test all branches

2.2.3 / 2019-10-24

  • (fix) Fix crash on spread (#94)

2.2.2 / 2019-10-24

  • (improvement) Add support for retrieving props from a spread with object expression (#93)

2.2.1 / 2019-06-30

  • (improvement) Account for TypeCastExpression in the utils

2.2.0 / 2019-06-25

  • (fix) Fix getLiteralPropValue for TS-specific node types.
  • (chore) upgrade dependencies.
  • (improvement) Stop throwing errors when unknown AST nodes are encountered.
  • (dev) CI changes.

2.1.0 / 2018-04-19

  • Fix undefined bug for template strings. #45
  • Adding support for objectRestSpread within props #60
  • Accommodate ExperimentalSpreadProperty in prop values #75
  • Account for SpreadElement AST Nodes #76
  • Support OptionalMemberExpression AST nodes #77
  • Add support to Typescript's node types #72

2.0.1 / 2017-08-31

  • [fix] Add support for BindExpression

2.0.0 / 2017-07-07

  • [breaking] Remove undefined return from propName so it always returns a value.

1.4.1 / 2017-04-19

  • [fix] - Fixing fatal throw in getPropValue for ArrowFunctionExpression

1.4.0 / 2017-02-02

  • [new] Add eventHandlers and eventHandlersByType to API. These are the event names for DOM elements on JSX-using libraries such as React, inferno, and preact.

1.3.5 / 2016-12-14

  • [fix] Normalize literals "true" and "false" before converting to boolean in Literal prop value extractor.

1.3.4 / 2016-11-15

  • [fix] Recursively resolve JSXMemberExpression names for elementType. (i.e. <Component.Render.Me />). Fixes #9

1.3.3 / 2016-10-28

  • [fix] Add support for ArrayExpression.

1.3.2 / 2016-10-11

  • [fix] Add support for UpdateExpression.

1.3.1 / 2016-07-13

  • [fix] Add JSXElement to expression types to handle recursively extracting prop value.

1.3.0 / 2016-07-12

  • [new] Add support for TaggedTemplateExpression.

1.2.1 / 2016-06-15

  • [fix] Point to lib instead of src for root exports.

1.2.0 / 2016-06-15

  • [new] Export functions from root so they can be imported like the following: require('jsx-ast-utils/{function}').

1.1.1 / 2016-06-12

  • [fix] Better support for expressions in TemplateLiteral extraction.

1.1.0 / 2016-06-10

  • [new] Support for namespaced element names.
  • [new] Add propName to API to get correct name for prop.

1.0.1 / 2016-06-10

  • [fix] Return actual reserved words instead of string representations of them.

1.0.0 / 2016-06-09

  • Initial stable release