[Vuejs]-How to compile SCSS to CSS and load the CSS code as string into a variable?

0đź‘Ť

From an initial look you have two problems here both of which are relatively simple.

The first one is you need to include a scss compiler plugin during your projects build step. Which one you use will depend on any existing tooling you may be using. Otherwise, you can just drop in https://www.npmjs.com/package/node-sass

The second issue is how to acquire the css at runtime. You have a couple options here. You can compile the file into your bundle or you could retrieve it at runtime.
Runtime would keep your bundle small and allow you to serve the css normally but this requires a server to serve it. Compile time would be faster to load initially but increase your bundle size.

If you are using webpack you could use the raw loader you linked but if you are not currently using webpack that is probably out of scope.

You could do this by adding a new step to your build that converts the css into a String literal which would alleviate the need to load it at runtime but increase your bundle side.

For loading at runtime, you could easily retrieve the file via ajax from an http server.

0đź‘Ť

I have found the following solution:

  1. Install the “raw-loader” loader
  2. Import the SCSS using the following statement:

    import style from '!raw-loader!sass-loader!./my-styles.scss'

Note: the “!” at the beginning is to override the default loaders configuration. In my case Quasar chains the “style-loader” for SCSS files by default (to output a tag in the head) so I have to disable it in this case.

And now I have the compiled CSS code in the style variable.

0đź‘Ť

First, run the following.

npm install path sass

Aftre that…

const path = require("path");
const sass = require("sass");

const css = sass.compile(path.join(__dirname, "style.scss")).css;
console.log(css);

Leave a comment