heroBy me

How to add SCSS or SASS to SvelteKit

Although Svelte/SvelteKit support other CSS preprocessors, nothing comes baked-in so we need to manually install dependencies in order to use them in our project. In this blog post, we'll go over the simplest way to achieve this.

For people who are new to Svelte or SvelteKit, the syntax for using SCSS or SASS is simple, just need to add lang="sass" attribute to style tag.

// SASS

<style lang="sass">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

// SCSS

<style lang="scss">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

However, if I try to do this in a new SvelteKit repository, I'll see the following error message.

sveltekit-error-no-sass

Here's the full error message:

Cannot find any of modules: sass,node-sass

Error: Cannot find module 'node-sass'
Require stack:
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/modules/utils.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/autoProcess.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/index.js

The file cannot be parsed because style requires a preprocessor that doesn't seem to be setup or failed during setup. Did you setup a `svelte.config.js`? If you use SCSS, it may be necessary to add the path to your NODE runtime to the setting `svelte.language-server.runtime`, or use `sass` instead of `node-sass`. 

See https://github.com/sveltejs/language-tools/tree/master/docs#using-with-preprocessors for more info.svelte(style)

Solution

All we have to do is add sass to our dev-dependencies, then SvelteKit will automatically pick it up.

There are a few packages we can use to achieve this:

  • node-sass is the one that is referenced the most, but since it has been deprecated I strongly recommend you avoid using this.
  • dart-sass is a more modern implementation of node-sass. But it has since been renamed to sass.
  • sass is the one you should use!
// NPM

npm i -D sass

// Yarn

yarn add -D sass

// PNPM

pnpm add -D sass

Then you should see the above error message disappear.

sass sveltekit error fixed

If the error message doesn't go away, try reloading your editor. If you use VS Code on a Mac, you can do this with cmd + p then search Developer: reload window.

Note: you may also need to restart the SvelteKit app for this to take effect.

Buy Me A Coffee