Accessibility Tree Shaking


Accessibility tree shaking refers to the risk that code optimization tools (webpack, Vite, PurgeCSS) unintentionally remove code necessary for assistive technologies. The .sr-only class, focus management utilities, aria-live announcements: this code invisible on screen can disappear in production without anyone noticing visually.


Your .sr-only class works in development. In production, it's gone. The screen reader no longer vocalizes the alternative text you added to your icon buttons. No visual test detects the problem. The culprit: your build tool, which eliminated the "unused" code.

#Why accessibility code is vulnerable

Tree shaking eliminates unused JavaScript exports. PurgeCSS and Tailwind's content scanning remove CSS classes absent from templates. These tools analyze code statically: they search for character strings in your source files.

Accessibility code has a particular trait: it is invisible by nature. A .visually-hidden class hides text on screen while keeping it in the accessibility tree. A JavaScript module managing aria-live announcements produces nothing visible. To an optimization tool, this code looks like dead code.

Three scenarios come up regularly.

Dynamic CSS classes. You build a class name through concatenation in JavaScript ('sr' + '-only'). PurgeCSS never finds the complete string sr-only in your templates. The class disappears from the final CSS bundle.

Misconfigured sideEffects: false. You declare your component library side-effect free in package.json. webpack removes CSS imports, including the stylesheet containing .visually-hidden.

Skip link styles purged. A skip link is only visible on keyboard focus. The purge tool detects no reference in static HTML and removes the associated styles.

#How to protect accessibility code

Two mechanisms are sufficient.

In CSS, add your accessibility classes to the safelist of your purge tool:

// tailwind.config.js
module.exports = {
  safelist: ['sr-only', 'visually-hidden', 'skip-link'],
}

In JavaScript, declare CSS files as having side effects:

{
  "sideEffects": ["*.css", "*.scss"]
}

The real safety net: integrate an automated accessibility test in your CI pipeline, on the production build. Not on the source code. This is the only way to catch a regression caused by bundle optimization.

#In summary

Tree shaking tools optimize what they understand: visible code. Accessibility code is invisible by design. Safelist your classes, declare your side effects, and test your production builds with an assistive technology.

Share this article

Learn more