michaelT
michaelT

Reputation: 1711

Node JS: Compile .scss file to .css and .map.css via node js script

I am new to node js, its structure and so on.

I am trying to compile a .scss file into a .css and .map.css file using a node js script. The script sass-dev.js is defined in my package.json:

"scripts": {
    "sass-dev": "node ./scripts/sass-dev.js"
},

So I can run the script via npm run sass-dev. The script itself works correctly, so it compiles the utility.scss into utility.css. But I want also that a source map utility.map.css is created. Therefore I defined sourceMap: true in the options, but no additional file is created.

So, how can I compile a .css and .map.css file from my .scss?

sass-dev.js:

const fs = require('fs');
const path = require('path');
const sass = require('sass');

const sassFile = path.join(__dirname, '../sass/utility.scss').toString();
const cssFile = path.join(__dirname, '../css/utility.css').toString();
const mapFile = path.join(__dirname, '../css/utility.map.scss').toString();

sass.render(
    {
        file: sassFile,
        sourceMap: true,
        outFile: mapFile,
    },
    (error, result) => {
        if (!error) {
            fs.writeFileSync(cssFile, result.css, function (err) {
                if (err) console.log(`Error appeared while writing file "${o}".`);
            });
        } else {
            console.log(error.formatted);
            console.log(`Error appeared in "${error.file}" !\nline: ${error.line}, column: ${error.column}\n${error.status}`);
        }
    }
);

Upvotes: 0

Views: 521

Answers (1)

Yoganathan Palaniswamy
Yoganathan Palaniswamy

Reputation: 383

In node-scss, setting the file paths will not automatically write the output to the file (both CSS and mappings), it is just used for references and you have to write the output to a file just like how you did for the CSS.

Also, outFile should be the path of the generated CSS file. If you set sourceMap to true, the map file will be automatically determined (by appending .map). Otherwise you can set sourceMap directly to a string to use that.

Finally, since you are using writeFileSync, you don't have to pass a callback function, simply wrap it around in try catch.

sass.render({
    file: sassFile,
    outFile: cssFile,
}, (err, result) => {
    if (err) {
        // Handle error
        return;
    }

    try {
        fs.writeFileSync(cssFile, result.css);
        fs.writeFileSync(mapFile, result.map);
    } catch (e) {
        // Handle error
    }
});

Upvotes: 1

Related Questions