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>
<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"
.module
to the SCSS file name (as per vue's docs)requireModuleExtension: false
(from same docs)https://codesandbox.io/s/importing-css-to-js-o9p2b?file=/src/App.vue
You need to add webpack
and CSS modular code into webpack.config.js
.
npm install -D vue-loader vue-template-compiler webpack
Here is the working demo
Note: your vue-template-compiler
and vue
should be the same version