SVG Linting Rules in ESLint Explained
SVG linting plugins in standard ESLint configurations evaluate inline SVG elements and SVG-in-JS components to ensure security, accessibility, structural optimization, and framework compatibility. These plugins analyze raw SVG markup within JSX, TSX, Vue, or template literals, enforcing strict standards before the code reaches production.
Security Rules
Security-focused SVG rules protect applications from Cross-Site Scripting (XSS) and injection vulnerabilities:
- Disallowing
<script>Elements: Flags and prohibits embedded<script>tags within SVG files or components to prevent arbitrary code execution. - Restricting Inline Event Handlers: Enforces the
removal of inline JavaScript event listeners, such as
onload,onclick, andonerror. - Sanitizing URIs and References: Validates
hrefandxlink:hrefattributes within<use>,<a>, or<image>tags to block dangerous URI schemes likejavascript:or external unauthorized domains. - Blocking Dangerous Elements: Prohibits tags such as
<foreignObject>,<embed>, or<object>unless explicitly allowed by configuration.
Accessibility (a11y) Rules
Accessibility rules ensure that SVG icons and illustrations are correctly interpreted by assistive technologies:
- Enforcing Meaningful Descriptions: Requires
informative SVGs to include a valid
<title>element, anaria-label, or anaria-labelledbyattribute. - Managing Decorative SVGs: Requires non-informative
or decorative icons to explicitly include
aria-hidden="true"orrole="presentation"to prevent screen reader noise. - Requiring Appropriate ARIA Roles: Validates that
<svg>tags intended as graphics userole="img"where necessary for cross-browser accessibility.
Optimization and Cleanliness Rules
These rules align with SVGO standards to eliminate bloat and maintain consistent asset formatting:
- Removing Unnecessary Metadata: Identifies and
removes editor artifacts, XML declarations, comments, and unused
namespaces (such as
xmlns:sketchorxmlns:inkscape). - Enforcing
viewBoxOver Hardcoded Dimensions: Warns against using hardcodedwidthandheightwithout aviewBox, ensuring the vector scales responsively across different container sizes. - Eliminating Redundant Attributes: Detects and
strips default attributes, empty containers, and unused
<defs>elements. - Precision and Path Formatting: Flags excessively high precision values in coordinate data to reduce bundle size.
Framework and Syntax Rules
When working in environments like React or Vue, plugins enforce syntax rules to prevent rendering errors:
- CamelCase Property Conversion: In JSX/TSX contexts,
rules require kebab-case SVG attributes (such as
stroke-widthorclip-path) to be written in camelCase (strokeWidth,clipPath). - Namespace Compatibility: Ensures namespace
attributes like
xmlns:xlinkare converted to standard JSX-compatible syntax (e.g.,xlinkHref). - Self-Closing Tag Enforcement: Enforces consistent
self-closing tags on empty elements like
<path />,<circle />, and<rect />.