Search code examples
vue.jssassnode-sassvue-cli-3

Use `chromatic-sass` in a Vue project (or make any JavaScript functions available in Sass files/blocks)


I want to use chromatic-sass in a Vue application generated by the Vue CLI 3 (@vue/cli).

However, chromatic-sass isn't written in SASS, so I can't @import it from a .scss file or <style lang="scss"> block. Because it's written in JavaScript (CoffeeScript to be exact), it needs to be bridged by configuring the SASS renderer.

Here's how the docs recommend integrating it into a project:

var sass = require("node-sass");
var chromatic = require("chromatic-sass");

sass.render({
  file: scss_filename,
  functions: chromatic
}, function(err, result) { /*...*/ });

The problem is, when using the Vue CLI, I don't have access to or control over how node-sass is used.

What's the easiest way I can get chromatic-sass working in a project generated by the Vue CLI? Is this possible via a config file modification?


I'm hoping for a complete answer (working code) rather than pointing me in a direction. The solution shouldn't otherwise modify how Vue handles SCSS files.

If it matters, the Vue CLI settings I used:

Vue CLI v3.3.0
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, CSS Pre-processors
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS
? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.?: In dedicated config files 

Solution

  • You should just pass needed options to SASS preprocessor.

    vue.config.js:

    const chromatic = require('chromatic-sass');
    
    module.exports = {
      css: {
        loaderOptions: {
          sass: {
            functions: chromatic
          }
        }
      }
    };
    

    I've tested it on newly created project using your settings and it works as expected.

    Documentation: Vue CLI 3 → Passing Options to Pre-Processor Loaders