Some good answers here, but there still seems to be some confusions in the answers, let me clear them up.
You need to update two files, svelte.config.js
and vite.config.js
to get this working.
Update svelte.config.js
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/kit/vite'; // Add this
const config = {
kit: {
adapter: adapter()
},
preprocess: [vitePreprocess()] // And this
};
export default config;
Update vite.config.js
This is the confusing part, since this config will vary from person to person and what you are trying to do.
- You must be using either
.scss
or .sass
, figure out which one you are using and don't mix them in the config.
- Figure out the path of your
.scss
or .sass
files that you want to include throughout the project. In this case, it's /src/lib/scss/
, for you it could be /src/
or /src/scss/
- With this config vite will include all the sass/scss and if some of them are actual styles and not just variables, those styles will be duplicated in the final bundle. For the same reason, we will use
@use
and not @import
.
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [sveltekit()],
// Add this
css: {
preprocessorOptions: {
// if using SCSS
scss: {
additionalData: `
@use '$lib/scss/variables' as *;
@use '$lib/scss/mixins' as *;
`,
},
// if using SASS
sass: {
additionalData: `
@use '$lib/sass/variables' as *;
@use '$lib/sass/mixins' as *;
`,
},
},
}
});
Usage
// src/lib/scss/_variables.scss
$color: red;
// src/lib/scss/_mixins.scss
@mixin big-font {
font-size: 32px;
font-weight: 900;
}
<!-- src/routes/+page.svelte -->
...
<style lang="scss">
h2 {
color: $color;
@include big-font;
}
</style>
To explicitly use variables and mixins you can give them an alias
scss: {
additionalData: `
@use '$lib/scss/variables' as vr;
@use '$lib/scss/mixins' as mx;
`,
},
<!-- src/routes/+page.svelte -->
...
<style lang="scss">
h2 {
color: vr.$color;
@include mx.big-font;
}
</style>