Caution: Sass @extend is tricky!
The dangers of Sass @extend
have been written
about many
times
before.
However, this is my personal short list of why I almost never use @extend
. Much of my reasoning below is based on years of experience
writing and maintaining codebases with 10,000 or 20,000+ scss lines of code. In smaller projects or codebases maintained by a single
developer these dangers become easier to manage. Hopefully the example below help you know when it’s time to reconsider your usage of
@extend
.
Compiled Footguns
Some of the dangers of @extend
are baked into the directive and liberal warnings
are given in the documentation. It is always worth a read if you have not studied it.
Media Queries
You are unable to extend a class inside a media query. This is a limitation which hints at other dangers, which do not produce compilation errors. We will consider a few of these next.
See the Pen @extend media queries by Kevin Muncie (@kmuncie) on CodePen.
Source Order
When using @extend
it can be difficult to keep track of the order to which the selectors will compile.
See the Pen @extend selector order by Kevin Muncie (@kmuncie) on CodePen.
1 | .global-green, .subtitle-modifier { |
Extending Everywhere
In a large project with many developers it can be hard to keep track of what is happening in the entire scss codebase. It thus requires extreme vigilance to ensure that any class you extend is only used as intended. It can be very hard for others to understand this intent when coming into a codebase for the first time.
Notice the following scss code and try to visualize what the compiled css will look like.
See the Pen @extend all over by Kevin Muncie (@kmuncie) on CodePen.
1 | .normal-boundary .outline, .normal-boundary .keep-it-dry .new-outline, .keep-it-dry .normal-boundary .new-outline { |
Is that what you expected? Do you think the developer who added @extend .outline
researched and knew about all the various instances of
.outline
throughout the codebase? Could you imagine _second-file.scss
and _third-file.scss
being added by other developers after
the @extend
had already been implemented without realizing the impact?
This is surely a contrived example but hopefully it is realistic enough to realize how slippery a slope @extend
can be.
Developer Brain Drain
Understanding Debug Tools
This is purely a personal preference but I find it very unpleasant to try and debug an element on a page which uses @extend
. The
properties are broken up and the selector blocks are massive. This puts you at the mercy of your browsers Dev Tools to be able to easily
read and digest what is happening. Not all browsers are good at this.