Sass compilation can be a speed bottleneck in your build, but it doesn’t have to be anymore.
Vite comes with built in support for Sass, as well as other CSS preprocessors.
Just npm install sass, import a .scss file, and it works.
However, this came with a catch. For every Sass import, a new instance of Sass
would spin up, compile, and spin down. If you have a single imported Sass entry
point file that imports other Sass files, this isn’t a big deal. But if you’re
using Vue’s Single File
Components (SFCs) with
lang="scss", you were spinning
up a new Sass instance for every single SFC.
That can add up.
Earlier this year, OddBird helped Sass add a new CompilerAPI that allows you
to reuse a single instance of Sass for multiple compilations. While you can
adopt the new API in your own bespoke Sass compilation setup, we were excited to
see the Vite team add support in version 5.4.0.
Vite 7.0 changed the available options
for compiling Sass, simplifying the process even more.
Update to Vite version 5.4.0 or above, and ideally 7.0 or above.
Switch from sass to sass-embedded by running npm uninstall sass; npm install -D sass-embedded.
Wait – what’s sass-embedded?
Sass is written in Dart. The sass package is transpiled to pure-Javascript,
and sass-embedded exposes the same API, but around a native Dart executable.
In many situations, sass-embedded is faster.
Vite 7.0 made the Sass Compiler API the default (and removed support for the
non-compiler API), so you don’t need to opt in to the API. For Vite 5.4.0
through < 7.0, you will need to opt in. In your vite.config.js file, set
css.preprocessorOptions.scss.api to modern-compiler.
...css:{preprocessorOptions:{// Set `sass` if using the indented syntaxscss:{// Only needed on versions < 7.0.0api:'modern-compiler',}}}...
Vite 7.0 also removed support for the legacy API. If you were using the
legacy API, adjust any options from the legacyAPI options to the
modernAPI options. In my case, I needed to update pkgImporter to
importers: [new NodePackageImporter()] and change the import of
NodePackageImporter from sass to sass-embedded.
And you’re done. Now your Vite compilation time should be even faster!
The benefit here is going to be very project-dependent. In our codebases,
we saw vite build times improving from ~4.7s to ~3.9s in a smaller project,
and from ~5.9s to ~3.8s in a larger project.
Others have
seen up to an 8x speed improvement. Incremental dev builds should also be
faster.
Let us know what kind of speed improvements you see in your projects!
I chat with Bruce Lawson about all things CSS. We geek out over the latest and greatest features like Cascade Layers, @Scope, Mixins, and Container Queries – exploring how these features impact web design.
onGeneral Musings with Kevin PowellwithMiriam Suzanneon
Kevin and I chat about getting involved with the development of the CSS language, from following along to opening issues, or even joining the CSS Working Group.