how to use sass using in vuejs3/vite

Viewed 23024

I starting with vite / vuejs 3

after installing sass with npm install -D sass I tried to add my _variables.js file this to vite.config.js

css: {preprocessorOptions: {scss: {additionalData: `@import" ./src/css/_variables.scss ";`,},},},

din't work!

it also worked in vue.config

css: {
     loaderOptions: {
       sass: {
         sassOptions: {
            prependData: `@import" @ / css / _variables.scss ";`,
         }
       }
     }
   },

after this tried to import the file in main.js import "./css/_variables.scss"

Unfortunately, my components cannot find the variables, where is the error

4 Answers

Vite is a litte bit different

    import { defineConfig } from 'vite'
    
    export default defineConfig({
      css: {
        preprocessorOptions: {
          scss: {
            additionalData: `
              @import "./src/styles/_animations.scss";
              @import "./src/styles/_variables.scss";
              @import "./src/styles/_mixins.scss";
              @import "./src/styles/_helpers.scss";
            `
          }
        }
      }
    })

here is my working setup, got it from the vite docs and with the command yarn add -D sass

// package.json
{
  "dependencies": {
   ...
    "vue": "^3.0.5"
  },
  "devDependencies": {
    ...
    "sass": "^1.32.11",
    "vite": "^2.2.3"
  }
}
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()]
})
// App.vue
<template>...</template>
<script>...</script>

<style lang="scss">
@import "./assets/style.scss";
</style>
// style.scss
[data-theme="dark"] {
  --bg-color1: #121416;
  --font-color: #f4f4f4;
}
[data-theme="light"] {
  --bg-color1: #f4f4f4;
  --font-color: #121416;
}
...
body {
  background-color: var(--bg-color1);
  color: var(--font-color);
}

and my vue.config.js is clean - nothing fancy there.

Solutions:

  1. "npm add -D sass" ---------- (-g flag will not work in vite now 16/02/2022). Or,

  2. "yarn add -D sass" - Run these comments in your command line.

  3. In main.js file "import './style.scss' " will not work, so I added my sass file in html

Related