3
votes

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

2
You're conflating CSS variables (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

2 Answers

6
votes

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

0
votes

It's possible to import SCSS variables generating .ts from .sccs file with scss-to-json package. The codesandbox demo.

I use the following steps described here.

  1. Install npm i --save-dev scss-to-json.

  2. Put this in your package.json:

"scripts": {
  ...
 "scss2json": "echo \"export const SCSS_VARS = \" > src/styles/scss-variables.generated.ts && scss-to-json src/styles/variables.module.scss >> src/styles/scss-variables.generated.ts"
 },

and run it with npm run scss2json. Windows users will need to adjust the example.

  1. Access the variables:
import {SCSS_VARS} from './styles/scss-variables.generated.ts';
...
console.log(SCSS_VARS["$variable"]);