Search code examples
node.jsnpmnode-sass

Compiling scss into css using node-sass with Node.js


I'm trying to compile my scss file into css file using node-sass , I already know how to do this with Command line. I have this npm-script In my package.json file :

"scripts": {
"scss": "node-sass --watch fileName/scss -o FileName/css"
}

and when I run :

npm run scss

it works fine. What I want to know is how to use (from the node-sass project page) :

var sass = require('node-sass');

sass.render({
  file: scss_filename,
  [, options..]
}, function(err, result) { /*...*/ });

I try this in my app.js :

var sass = require('node-sass');

sass.render({
  file: __dirname + '/scss/style.scss',
  outFile: __dirname + '/css/style.css',
}); 

but it's not working, I have little experience with this and I can use some help.


Solution

  • within the same documentation you linked to

    sass.render({
        ...
        outFile: yourPathTotheFile,
      }, function(error, result) { // node-style callback from v3.0.0 onwards
        if(!error){
          // No errors during the compilation, write this result on the disk
          fs.writeFile(yourPathTotheFile, result.css, function(err){
            if(!err){
              //file written on disk
            }
          });
        }
      });
    });
    

    the sass.render() doesn't write to the file, it only passes the result to a callback. You need to write it yourself using fs as in the example above.