#StackBounty: #vue.js #vue-cli-3 #css-modules Can't access CSS variables in script tag of Vue file

Bounty: 50

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


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.