使用 node-sass 和 Node.js 将 scss 编译成 css

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

我正在尝试使用 node-sass 将我的 scss 文件编译成 css 文件,我已经知道如何使用命令行执行此操作。 我的 package.json 文件中有这个 npm-script

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

当我 运行 :

npm run scss

它工作正常。 我想知道的是如何使用(来自node-sass项目页面):

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

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

我在 app.js 中尝试这个:

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

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

但它不起作用,我对此经验不足,需要一些帮助。

在您链接到的同一文档中

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
        }
      });
    }
  });
});

sass.render() 不会写入文件,它只会将 result 传递给回调。您需要使用 fs 自己编写,如上例所示。