Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Last active November 22, 2024 11:49
Show Gist options
  • Save JamieMason/b7aa3322b7790848126c1c5bc0df7c88 to your computer and use it in GitHub Desktop.
Save JamieMason/b7aa3322b7790848126c1c5bc0df7c88 to your computer and use it in GitHub Desktop.
Find `img` or `Image` JSX Elements with a missing `width` or `height`

Find img or Image JSX Elements with a missing width or height

View this on the ast-grep Playground

1. Install ast-grep

See https://ast-grep.github.io/guide/quick-start.html#installation

2. Create sgconfig.yml

ruleDirs:
  - rules

3. Create rules/image-without-dimensions.yml

id: image-without-dimensions
language: JavaScript
rule:
  kind: jsx_self_closing_element
  all:
    - has:
        kind: identifier
        regex: ^(img|Image)$
    - any:
        - not:
            has:
              kind: jsx_attribute
              has:
                kind: property_identifier
                regex: ^width$
        - not:
            has:
              kind: jsx_attribute
              has:
                kind: property_identifier
                regex: ^height$

message: Image must have both a width and height attribute
severity: warning

4. Run

sg scan --context 30

Example output

warning[image-without-dimensions]: Image must have both a width and height attribute
   ┌─ components/app-promo.tsx:35:14
   │
35 │               >
   │ ╭─────────────^
36 │ │               <img
   │ │                ---
37 │ │                 src="/img/itunes-button.png"
38 │ │                 alt="Download on the App Store"
39 │ │                 height={48}
40 │ │               />
   │ ╰────────────────^

warning[image-without-dimensions]: Image must have both a width and height attribute
   ┌─ components/app-promo.tsx:47:14
   │
47 │               >
   │ ╭─────────────^
48 │ │               <img
   │ │                ---
49 │ │                 src="/img/play-store-button.png"
50 │ │                 alt="Get it on Google Play"
51 │ │                 width={160}
52 │ │               />
   │ ╰────────────────^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment