0

I have a collection of variables in a JSON file that I'm trying to share between styles (SCSS) and my Vue 3 (using the Vue CLI) environment.

./vars.json

{
  "foo": 123,
  "bar": "abc"
}

Getting the JSON into the script side's consciousness is the easy part. I'm stumped as to how to get the variables into the SCSS. According to the reference (Vue CLI Docs, among them) I could find online, my best bet is injecting them via prependData in the sass (loader) configuration in vue.config.js.

vue.config.js

const varData = require( "./vars.json" );

function jsonVarHelper() {
  let string = "";
  for (var variableName in varData) {
    string += `$${variableName}: ${varData[variableName]};\n`;
  }
  return string;
}

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        prependData: `@import "@/styles/main.scss";\n${jsonVarHelper()}`
      }
    }
  }
};

… which is rendering "$foo: 123;\n' + '$bar: abc;\n'" — which I confirmed by spitting out a console.log( {string} ) in jsonVarHelper. It was further confirmed in that I could use the variables in the Vue components' <style> sections.

./src/App.vue (omitting <template> and <script> for brevity)

<style lang="scss">
#app::after {
  content: "#{ $bar }"; // appends "abc" as expected
}
</style>

Sure enough, #app has the string "abc" appended to it in the compiled page. Great, right? Problem solved…

But, when I try to reference the variables in *.scss files, WebPack throws a syntax error.

./src/styles/main.scss

#baz::after {
  content: "#{ $bar }"; // throws `Syntax Error: SassError: Undefined variable: "$bar".`
}

I'm guessing this is a matter of when the scss-loader is prepending the data from the prependData configuration. Is it possible to have it parse/inject that string before it tries to compile the native *.scss files?

Ito Pizarro
  • 1,607
  • 1
  • 11
  • 21

0 Answers0