Search code examples
vue.jsvue-cli-3css-modules

Can't access CSS variables in script tag of Vue file


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 &lt;script&gt;, the variable is {{variable}}</p>
// 'not found', should be "foo"
<p>Importing within &lt;style&gt;, 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


Solution

  • 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