What's new
  • Do not create multi-accounts, you will be blocked! For more information about rules, limits, and more, visit the Help Page Found a dead link? Use the report button!
  • If no files are available, please contact me or reply in the thread. I will update them immediately.

How to import SASS file as inlined CSS (not JS) in SvelteKit/Vite

To import a SASS file as inlined CSS (not JavaScript) in a SvelteKit project using Vite, you can configure the project to directly process the SASS file and include it in the final CSS output without embedding it in JavaScript. Here’s how you can achieve this:


---

Steps:

1. Install Required Dependencies

First, ensure you have the required packages installed:

JavaScript:
npm install sass vite-plugin-sass-dts -D

---

2. Set Up SASS Files

Create your SASS file, for example, src/styles/global.scss:
JavaScript:
// global.scss

body {

  font-family: 'Arial', sans-serif;

  background-color: #f0f0f0;

}



h1 {

  color: #333;

}





---

3. Update vite.config.js

Modify your vite.config.js (or vite.config.ts) to ensure SASS files are processed and included as part of the final CSS build output:

JavaScript:
import { defineConfig } from 'vite';

import svelte from '@sveltejs/vite-plugin-svelte';



export default defineConfig({

  plugins: [svelte()],

  css: {

    preprocessorOptions: {

      scss: {

        additionalData: `@import "src/styles/global.scss";`

      }

    },

  },

});





---

4. Reference the SASS File

Add your SASS file in your Svelte project:

In your src/routes/+layout.svelte or src/app.html:

JavaScript:
<script>

  import '/src/styles/global.scss'; // Vite will inline this CSS directly

</script>





---

Alternative (For Global Styles):

If you want the SASS file directly included in the <head> without importing it into JavaScript, create a src/app.html file and include it manually:

src/app.html:

JavaScript:
<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="utf-8" />

    <link rel="stylesheet" href="/src/styles/global.css">

  </head>

  <body>

    <div id="svelte"></div>

  </body>

</html>

Vite will handle converting the SASS file into global.css during the build process.


---

5. Build Your Project

Run your development server or build your SvelteKit project:

JavaScript:
npm run dev

# or

npm run build


---

How It Works:

The css.preprocessorOptions in the Vite config ensures SASS files are correctly processed.

Including the global.scss file directly in the <head> or importing it ensures the styles are treated as inlined CSS, not part of the JavaScript bundle.
 
Back
Top