Search code examples
sassgruntjsnode-sass

How to use functions in grunt-sass?


My current project uses grunt-sass to translate scss files into css. According to the grunt-sass documentation, I can use any option that node-sass provides except for a few:

Options

See the node-sass options, except for file, outFile, success, error.

My project compiles two CSS files out of one SCSS file. The SCSS file has if-statements in it that provides different code depending on the value of the version variable ($bootstrap-version: 3; or $bootstrap-version: 4;).

I would like to use the node-sass option functions to return the bootstrap version to my SCSS files.

Here's my gruntfile. The functions: {...} path is how I would have expected the option to work.

// Compile Sass
sass: {
bootstrap3: {
    options: {
      style: 'expanded'
      functions: {getBootstrapVersion: function(){return 3;}}
    },
    files: {
      'dist/bootstrap3/css/my-bs3-variation.css': './bootstrap3/scss/my-bs3-variation.scss'
    },
},
bootstrap4: {
    options: {
      style: 'expanded',
      functions: {getBootstrapVersion: function(){return 4;}}
    },
    files: {
      'dist/bootstrap4/css/my-bs4-variation.css': './bootstrap4/scss/my-bs4-variation.scss'
    }
}

In the SCSS file, I call the function like this:

$bootstrap-version: getBootstrapVersion();

h1:before {
    content: "Bootstrap " + $bootstrap-version + " Version of ";
}

However, when trying to compile it, I get the errir >> Error: error in C function getBootstrapVersion: A SassValue object was expected. for the line where I call the function.

The example in the node-sass documentation does not help me much. What did I do wrongly? Or are there any better examples out there that I just did not find?

I use grunt-sass version 2.0.0 and node-sass version 4.7.2


Solution

  • The functions must return a SassValue object.

    Unfortunately, I don't believe it is possible to do that with grunt-sass alone because we need to wrap your returned numbers 4 and 3 in typing functions defined in node-sass (which grunt-sass does not expose...).

    For example, with node-sass in javascript, one may use something like sass.types.Number(4) to declare 4 as a Number SassValue.

    Here, sass is the node-sass import const sass = require('node-sass');, which is not available in grunt...