Problem
I am trying to access variables defined within an SCSS file from a .vue
file. The project is using vue-cli.
According to Vue's docs:
"Vue CLI projects comes with support for PostCSS, CSS Modules and pre-processors including Sass, Less and Stylus."
However, if I create a variables.css
file with a variable called variable
, and try to import it within the script, this variable
is not found.
styles/variables.module.css
$variable: 'foo';
:export {
variable: $variable
}
App.vue
<script>
import variables from "./styles/variables.module.scss";
export default {
name: "App",
methods: {},
computed: {
variable() {
console.log(variables); // Object {}
return variables.variable || "not found";
}
}
};
</script>
Importing the variables.css file within the <style module>
tag of the same vue file does work however.
App.vue
<style module lang="scss">
@import "./styles/variables.module.scss";
:export {
variable: $variable;
}
</style>
What I'm trying to achieve
<p>Importing within <script>, the variable is {{variable}}</p>
// 'not found', should be "foo"
<p>Importing within <style>, the variable is {{$style.variable}}</p>
// correctly showing "foo"
Have tried:
- Adding
.module
to the SCSS file name (as per vue's docs) - Creating a vue.config.js file with
requireModuleExtension: false
(from same docs)
Reproducible demo
https://codesandbox.io/s/importing-css-to-js-o9p2b?file=/src/App.vue
property: var(--some-name)
) with SCSS variables. They are different type of variables used for different purposes (CSS variables work in real time and can be parsed by CSSOM parser (browser), while SCSS variables are used by pre-processors to create CSS from SCSS) and can be parsed by SCSS/SASS parsers. On the bright side, as pointed out by @tuhin's answer, SCSS variables can be imported into.(ts|js)
files while CSS variables not so much (although I might not be up to date with latest news on this front). – tao