Node Sass Ultimate Guide for Seamless CSS Preprocessing

Introduction to Node-Sass

Node-sass is a library that provides binding for Node.js to LibSass, a Sass compiler. It allows you to natively compile .scss files to CSS at incredible speed and provides a powerful API for usage within JavaScript applications.

Installation

 npm install node-sass 

Basic Usage

To compile a Sass file to CSS using node-sass, you can use the following code:

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

 sass.render({
   file: 'path/to/your/file.scss',
 }, function(error, result) {
   if (!error) {
     console.log(result.css.toString());
   } else {
     console.error(error);
   }
 });

API Examples

Rendering Synchronously

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

 const result = sass.renderSync({
   file: 'path/to/your/file.scss'
 });

 console.log(result.css.toString());

Using Data Option for String Input

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

 sass.render({
   data: 'body {background: #000; color: #fff;}',
 }, function(error, result) {
   if (!error) {
     console.log(result.css.toString());
   } else {
     console.error(error);
   }
 });

Output Style

You can specify the output style for your CSS:

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

 sass.render({
   file: 'path/to/your/file.scss',
   outputStyle: 'compressed'
 }, function(error, result) {
   if (!error) {
     console.log(result.css.toString());
   } else {
     console.error(error);
   }
 });

Custom Importer

You can define custom importers to handle specific import path resolution:

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

 sass.render({
   file: 'path/to/your/file.scss',
   importer: function(url, prev, done) {
     if (url === "custom") {
       return { file: "some/other/file.scss" };
     } else {
       return done({ file: url });
     }
   }
 }, function(error, result) {
   if (!error) {
     console.log(result.css.toString());
   } else {
     console.error(error);
   }
 });

Combining APIs in an Application

Here’s an example of using node-sass within a typical Node.js application to dynamically compile Sass to CSS and serve it with an Express.js server:

 const express = require('express');
 const sass = require('node-sass');
 const app = express();

 app.get('/styles.css', function(req, res) {
   sass.render({
     file: 'path/to/your/file.scss'
   }, function(error, result) {
     if (!error) {
       res.set('Content-Type', 'text/css');
       res.send(result.css);
     } else {
       res.status(500).send(error);
     }
   });
 });

 app.listen(3000, function() {
   console.log('Server running on port 3000');
 });

With this setup, requests to /styles.css are compiled from file.scss on-the-fly, ensuring the latest changes are always reflected without manual compilation.

Hash: f440d81f8c795e7b17c0e92df5127c6d8f9c110f5c03c7a43f27f962920feae0

Leave a Reply

Your email address will not be published. Required fields are marked *