Search code examples
javascriptsassnode-sass

node-sass - How to use a wildcard directory value in output path


Is there a way for node-sass to use the variable in it's output path? I'm trying to do something like the following:

node-sass blocks/**/editor.scss -o dist/$1-editor.css

The goal is to prefix the output with the value of it's parent directory. For example, a directory structure of:

blocks
├── foo
│   ├── editor.scss
├── bar
│   ├── editor.scss
└── baz
    └── editor.scss

would result in the following compiled CSS filenames:

dist
├── foo-editor.css
├── bar-editor.css
└── baz-editor.css

The above command currently outputs:

dist
└── -editor.css

The $1 prefix is ignored.


Solution

  • At least, this can be done in node.

    const fs = require("fs");
    const sass = require("node-sass");
    
    fs.readdirSync("blocks").forEach(dir => {
      sass.render(
        {
          file: `blocks/${dir}/editor.scss`,
          outFile: `dist/${dir}-editor.css`
        },
        (error, result) => {
          if (!error) {
            fs.writeFile(`dist/${dir}-editor.css`, result.css, error => {
              if (error) {
                console.log(err);
              } else {
                console.log(`dist/${dir}-editor.css`);
              }
            });
          }
        }
      );
    });