Using SCSS Variables in JavaScript with Vue 3
Project Setup
Create a new Vue 3 project using Vite:
npm init vite@latest my-project
# Choose Vue template
cd my-project
npm install
npm install sass
Creating SCSS Variables
Create a file named src/styles/theme.module.scss:
$primary-color: #ff461f;
$secondary-color: #065279;
:export {
primary: $primary-color;
secondary: $secondary-color;
}
The .module.scss extension is required for CSS modules in Vite projects when importing into JavaScript.
Importing in Components
Use the varibales in your Vue components:
<template>
<div>
<h1 :style="{ color: theme.primary }">Hello World</h1>
<p :style="{ backgroundColor: theme.secondary }">Styled text</p>
</div>
</template>
<script setup>
import theme from '@/styles/theme.module.scss'
console.log(theme)
// Output: { primary: '#ff461f', secondary: '#065279' }
</script>
The :export directive in SCSS makes variables accessible as a JavaScript object when imported.