How to use sass global variables from other components in vite/vue3
Asked Answered
H

2

13

I want to use and change global variables from other components, my files structure looks like this...

enter image description here

I have my variables in global.sass file, but I can't access variables in other components.

Hackery answered 25/1, 2022 at 13:20 Comment(0)
N
33

You need to set configuration file vite.config.js :

css: {
  preprocessorOptions: {
    scss: {
      additionalData: `@import "@/assets/global.scss";`
    }
  }
},

also for local fonts you can add another configuration there, set alias:

resolve: {
  alias: {
    '@': path.resolve(__dirname, 'src'),
  }
},

and then use it something like:

@font-face {
  font-family: 'Opensans-Bold';
  font-style: normal;
  src: local('Opensans-Bold'), url(@/assets/fonts/OpenSans-Bold.woff2) format('woff2');
}
Nutation answered 25/1, 2022 at 13:56 Comment(2)
Just an FYI if anyone comes across this looks like the link has moved vitejs.dev/config/shared-options.html#css-preprocessoroptionsWyler
@Nikola Pavicevic does the code you write in vite.config.js file and the @import that you used in that work similar to @import that sass docs mentioned? If yes, do you have any solution that works similar to @use that is recommended by sass and also works globally?Sisk
B
12

A new sass module system

Note: The Sass team discourages the continued use of the @import rule. Sass will gradually phase it out over the next few years, and eventually remove it from the language entirely. Prefer the @use rule instead. (Note that only Dart Sass currently supports @use. Users of other implementations must use the @import rule instead.)

More details: Here

Below is the best way to global scss at that time.

vite.config.js

export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "~/styles/_main.scss" as *;`,
      },
    },
  },
  plugins: [vue()],
});

styles/abstracts/_colors.scss

$default: #000000;
$default-light: #333333;
$default-dark: #000000;

styles/abstracts/index.scss

@forward './colors';
@forward ...

styles/_main.scss

@forward './abstracts';
@forward './components';
@forward './layouts';

src/index.scss => don't forget to add this import "./index.scss" in App.vue

@forward './styles/abstracts';
@use './styles/abstracts' as *;

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
}

body {
  font-family: $font-primary;
  font-size: 1.6rem;
  line-height: 1.5;
  text-rendering: optimizespeed;
  color: $text;
  overflow-y: overlay;
}
Binford answered 8/1, 2023 at 8:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.