node-sass-self-contained-importer

Used to execute sass/scss import and meanwhile resolve relative asset paths declared in the imported file as relative to the importing file. This plugin works as an importer for node-sass, so it supports gulp.js.

Usage no npm install needed!

<script type="module">
  import nodeSassSelfContainedImporter from 'https://cdn.skypack.dev/node-sass-self-contained-importer';
</script>

README

node-sass-self-contained-importer

NPM

Used to execute sass/scss import and meanwhile resolve relative asset paths declared in the imported file as relative to the importing file. This plugin works as an importer for node-sass, so it supports gulp.js.

Usage

var fs = require("fs");
var importer = require("node-sass-self-contained-importer");
var sass = require("node-sass");

var compile = function(cssFile){
  var outFile = path.basename(cssFile, path.extname(cssFile)) + ".css";
  var result = sass.renderSync({
    file: cssFile,
    outFile: outFile,
    importer: importer,
  });
  result = result.css.toString();
  
  var fdw = fs.openSync(outFile, "w");
  var buf = Buffer.from(result);
  fs.writeSync(fdw, buf, 0, buf.length);
  fs.closeSync(fdw);
};

compile("main.scss");

Note

1. node-sass version

Node-sass of version >= 3.0.0 is required.

2. node-sass option - outFile

Node-sass option outFile is required so this plugin can determine the final referring file to adjust asset reference as relative to final output file.

3. node-sass option - data

When using data rather than file to compile, you should attach a key named filePath on importer so this plugin can know where to start to adjust asset reference and import file, like:

importer.filePath = currentHtmlFile;
sass.renderSync({
    data: scssContent,
    outFile: outFile,
    importer: importer,
});