For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogWeb Developmentnode-sass: Binding for Node.js to LibSass

node-sass: Binding for Node.js to LibSass

Published
05th Sep, 2023
Views
view count loader
Read it in
12 Mins
In this article
    node-sass: Binding for Node.js to LibSass

    Node sass is a library that allows binding for Node.js to LibSass, the C version of Sass's stylesheet preprocessor. It compiles .scss files to CSS with speed and automatically through connected middleware. SASS (Syntactically Awesome Style Sheets) is a comprehensive version of CSS. It allows developers to build code in another language, translate it into CSS, and compile SASS to CSS at an incredible speed.

    It has introduced various new features like: 

    • nesting 
    • data variables 
    • mixin functions 
    • and many more! 

    The newer one uses the .scss extension, and the older one uses the .sass extension.

    It was initially developed by Hampton Catlin and then designed by Natalie Weizenbaum. After its initial renditions, Weizenbaum and Chris Eppstein have continued to extend SASS with SassScript. It supports four data types: Numbers, Strings, Colors, and Booleans. Nesting also works in this language. 

    Knowledgehut is globally recognized as the Market Leader in providing Training to corporates and professionals. Our highly experienced Programming Expert Team provides Training in a Full Stack developer course, and they have more than 15 years of experience. The specialized instructors have developed unique teaching methods to help enthusiastic candidates master the skills to write Node.js certifications. 

    Getting Started with Node SASS 

    There are options of using the original Ruby gem, the Node.js port, or task runners such as Gulp or Grunt on the command line. If not comfortable using a GUI, several recommendations include Compass, CodeKit, or Hammer. 

    Let us start with Node SAAS 

    Installation Methods 

    SAAS can be installed in a few ways 

    1. Sass that requires Ruby 
    2. Node-Sass that runs on Node.js 
    3. Application Tool that include Sass 

    Installation of Sass Requires Ruby 

    Sass/SCSS are compiled using Ruby; Ruby must be installed on your system before Sass is installed. 

    Ruby Installation on a Macintosh (MAC) 

    Ruby is pre-installed on all Macintosh computers. 

    Ruby Installation on a Computer Running Windows 

    Use the Ruby installer to install on a Windows computer. Ruby command-line PowerShell application also gets installed along when installed through the installer. It provides access to Ruby libraries. 

    1. Sass Installation (requiring Ruby) through Command Line

    Ruby utilizes gem to handle its various packages of code, including Sass. 

    1. In Macintosh, open the Utility folder and then click the Terminal. app. 
    2. On a Windows computer, run cmd. 

    For all Mac, Windows, Linux installation methods, install Sass gem first: 

    gem install sass 

    Type as below to check and ensure Sass is installed

    Sass -v 

    Enter the below command sass input to run Sass from the command

    line.scss output.css 

    Ruby Sass should no longer be used, and will no longer be receiving any updates. 

    2. Node-Sass that runs on Node.js

    Install Node.js to run Node-Sass. For more information, click here to learn about installing Node and NPM

    Once Node is installed, use the Command Line to install Node-Sass 

    npm install node-sass 

    Running Node-Sass 

    Execute Sass with a Visual Studio Code Task Runner.

    It can also run with Node-Sass with the Command Line 

    node-sass input.scss output.css 

    Note: 

    The Command-Line is used often for Sass to process your SCSS files. Task runners like Gulp or Grunt manage Sass or Less files. They are usually JavaScript that handles different tasks for a website platform. It also handles preprocessing of Sass, scanning for syntax issues, and manages to concatenate/minify the files. Integrated development environments (IDE) handle processing your Sass or Less files. e.g., IDEs include Visual Studio Code, Sublime Text, Atom, and WebStorm. 

    3. Application Tools

    Different applications are available for Sass and Less. Below are some of the applications available 

    CodeKit: CodeKit is a GUI interface dealing with Sass and Less and is available only on the Mac.

    Compass.app: Compass. The app is a universal multi-platform GUI which is a framework for Sass.

    GhostLab: GhostLab is a Mac-based app that compiles Sass and tests responsive design across different devices and browsers.

    Hammer: Hammer is used for web development for Mac that automatically compiles Sass to HTML, CSS, and JavaScript.

    Koala: Koala is a GUI application for Sass and Less and runs on Mac, Windows, and Linux that offers real-time compilation. 

    LiveReload: LiveReload is available for Mac, Windows, and Linux that compiles Sass and monitors modifications in the file system. 

    Prepros: Prepros runs on Mac, Windows, and Linux and is a tool that compiles Sass and Less with automatic CSS prefixing and incorporates a built-in server for cross-browser testing. 

    Scout: Scout runs on Mac and Windows and runs Sass and Compass in a self-contained Ruby environment. 

    Want to know about the FSD certification? Check out the Full Stack Development Course here. 

    Working with Node SASS

    Sass is the most popular of the CSS pre-processors as it has helped to write neat, reusable, and modular CSS. This section shows how to compile Sass into CSS using the command line and use SASS. 

    Install Node.js

    To compile Sass via the command line, install Node.js. Download it on nodejs.org. Open the downloaded package and follow the wizard to install. 

    Initialize NPM

    NPM is the Node Package Manager for JavaScript. NPM effortlessly installs and uninstalls third-party packages. Open your terminal to initialize a Sass project with NPM and CD (change directory) to your project folder. 

    >> cd /users/Your username/Project 

    Run the command npm init after you are in the correct folder. NPM generates a package.json file in your folder after answering a few questions. 

    Install Node-Sass

    Node-sass helps to compile Sass to CSS. Execute the following command in the terminal to install node-sass:

    npm install node-sass 

    Write Node-sass Command

    We are ready to write a small script that compiles to Sass. Open the package.json file in the editor: 

    { 
    "name": "sass-help", 
    "version": "1.0.0", 
    "description": "", 
    "main": "index.js", 
    "scripts": { 
    "test": "echo \"Error: nothing specified\" && exit 1" 
    }, 
    "author": "", 
    "license": "ISC" 
    } 
    Add an scss command in the scripts section under the test command. 
    "scripts": { 
    "test": "echo \"Error: nothing specified\" && exit 1", 
    "scss": "node-sass --watch scss -o css" 
    } 

    Below are a few quick go through points. 

    1. node-sass: Directs to the node-sass package. 
    2. watch: This means all .scss files in the scss/ folder should be recompiled every time if there’s a change added. 
    3. scss: Folder where all our .scss files are stored. 
    4. o css: Output folder for all compiled CSS. 

    Execute this script, and every .scss file in the scss/ folder is watched, and then all compiled css are saved in the css/ folder. 

    Run the Script

    To execute our one-line script run the below command in the terminal:

    npm run scss 

    Hurray! We can now watch the compiled SASS. 

    Using Sass to style your React Native Components

    Use create-react-app in the project and easily install and use Sass in React projects

    Install Sass by executing the command in the terminal: 

    >npm i sass 

    We are ready to include Sass files in the project! 

    Sass file to be created 

    Create a Sass file in the same way as CSS files are created, but Sass files have the extension .scss 

    Use variables in the .scss files and other Sass functions: 

    my-sass.scss: 
    Define a variable for the color of the text: 
    $myColor: red; 
    h1 { 
    color: $myColor; 
    } 
    Import the Sass file as it is done for a CSS file: 
    index.js: 
    import React from 'react'; 
    import ReactDOM from 'react-dom'; 
    import './my-sass.scss'; 
    const Header = () => { 
    return ( 
    <> 
    <h1>Hello Car!</h1> 
    </> 
    ); 
    } 
    ReactDOM.render(<Header />, document.getElementById('root')); 

    Using Variables in Sass

    Variables help to store information that can be reused later when required. 

    Information can be stored in the following data types 

    • strings 
    • numbers 
    • colors 
    • booleans 
    • lists 
    • nulls 

    $ symbol, followed by a name, is used to declare variables 

    mystyle1.scss 
    $myFont: Helvetica, sans-serif; 
    $myColor: red; 
    $myFontSize: 18px; 
    $myWidth: 680px; 
    body { 
    font-family: $myFont; 
    font-size: $myFontSize; 
    color: $myColor; 
    } 
    mystyle1.css 
    #container { 
    width: $myWidth; 
    } 
    body { 
    font-family: Arial; 
    font-size: 16px; 
    color: blue; 
    } 
    #container { 
    width: 680px; 
    border: 1px blue double; 
    } 
    mypage1.html 
    <!DOCTYPE html> 
    <html> 
    <link rel="stylesheet" href="mystyle1.css"> 
    <body> 
    <h1>Hello World.</h1> 
    <p>This is the first paragraph.</p> 
    <div id="container">This is text placed inside a container.</div> 
    </body> 
    </html> 

    Using Inheritance in Sass

    In Sass, @extend is used for sharing CSS properties.

    It is one of the most significant components of Sass. 

    Using Sass's @extend feature, a set of properties can be shared between classes. @extend features make the code simpler to write and easier to rewrite. 

    Syntax: 

    @extend .class-name; 

    In Sass, @extend is used for sharing CSS properties.

    It is one of the most significant components of Sass. 

    Using Sass's @extend feature, a set of properties can be shared between classes. @extend features make the code simpler to write and easier to rewrite. 

    Syntax: 

    @extend .class-name; 

    The .trial1 class is derived from the .trial class and has the same properties as .trail. 

    style1.scss 
    .trail{ 
    color: black; 
    border: 1px solid black; 
    } 
    .trail1{ 
    @extend .trail; 
    background-color: rgb(52, 40, 224); 
    } 

    Using Operators in Sass

    Sass has a handful of operators for different values.

    Standard mathematical operators like + and * and other operators as below: 

    1. == and != checks two values. 
    2. +, -, *, /, and % have mathematical meanings for numbers in scientific math. 
    3. <, <=, >, and >= check two numbers more or less than another. 
    4. And, or, and not have the usual Boolean behavior.
    5. +, -, and / are used to concatenate strings. 

    Order of Operations

    Below is the order of operations in SASS: 

    1. The unary operators not, +, -, and /. 
    2. The *, /, and % operators. 
    3. The + and - operators. 
    4. The >, >=, < and <= operators. 
    5. The == and != operators. 
    6. The and operator. 
    7. The or operator. 
    8. The = operator 

    @debug 4 + 6 * 3 == 1 + (2 * 3) // false 

    @debug true or false and false == true or (false and false) // true 

    Node Sass Example

    A simple web project that utilizes the node-sass module. 

    $ mkdir sass 
    $ mkdir -p public/css 
    Create three subdirectories.
    We have the SCSS code sass directory. The translated SCSS code into CSS is moved into the public/css directory. 
    $ npm init -y 
    We initiated a new Node application. 
    $ npm i node-sass 
    We install the node-sass module.
    $ npm install -g live-server 
    Install live server, a little development server with live reload capability. 
    package.json 
    { 
    "name": "nodesass-ex", 
    "version": "1.0.0", 
    "description": "", 
    "main": "index.js", 
    "scripts": { 
    "sass": "node-sass -w sass -o public/css" 
    }, 
    "keywords": [], 
    "author": "Tom Blair", 
    "license": "BSD", 
    "dependencies": { 
    "node-sass": "^5.0.0" 
    } 
    } 

    Run the script that runs the node-sass module. The output compiled is moved into the public/css directory. 

    public/index.html 
    <!DOCTYPE html> 
    <html lang="en"> 
    <head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <link rel="stylesheet" href="css/main.css"> 
    <title>Home page</title> 
    </head> 
    <body> 
    <div class="container"> 
    <h1>Bug History</h1> 
    <table> 
    <tr> 
    <th>Bugs</th> 
    <th>Description</th> 
    </tr> 
    <tr> 
    <td>DOD bug</td> 
    <td>The bug has wiped all the data from all the machines in the network</td> 
    </tr> 
    <tr> 
    <td>Bed bugs</td> 
    <td>They are parasitic insects that suck blood.</td> 
    </tr></table></div>
    </body> 
    </html> 

    The document is styled with CSS. 

    <link rel="stylesheet" href="css/main.css"> 
    sass/main.scss 
    $myfont: Georgia 1.1em; 
    $table_head_col: #ccc; 
    $table_row_col: #eee; 
    $table_bor_col: #eee; 
    $container_width: 700px; 
    $first_col_width: 150px; 
    div.container { 
    margin: auto;
    font: $myfont; 
    width: $container_width; 
    } 
    table { 
    tr:nth-child(odd) {background: $table_row_col} 
    td:first-child {width: $first_col_width} 
    th { 
    background-color: $table_head_col; 
    } 
    border: 1px solid $table_bor_col; 
    } 

    SCSS code styles the container and the table.

    The commands are executed in separate terminals 

    $ npm run sass 
    We run the sass script. 
    $ live-server --open=public 

    We can view the output on the live server. 

    Looking to enhance your coding skills? Discover the power of Python! Learn this versatile language with our Python certification program. Unleash your potential today!

    Conclusion

    Sass is an excellent tool for website developers to enhance their web design with essential programming functions. Sass language and syntax are quick to learn and easy to install. 

    The different programming functions, such as mixins and variables, and the visual hierarchy of Sass make it more efficient and maintainable stylesheets. I hope this article will provide enough information about the SASS, a cutting-edge technology. 

    Knowledgehut Node.js certification training  assists learners in gaining in-depth knowledge and skills for building front-end and back-end web applications. 

    Frequently Asked Questions (FAQs)

    1Is Node sass deprecated?

    Warning: LibSass and Node Sass are deprecated. They will persist and continue to receive maintenance releases indefinitely. There are no plans to add extra features or compatibility with new CSS or Sass features. Projects created in SASS should be moved onto Dart Sass. 

    2Why do we need Node sass?

    Node-sass is a library providing binding for Node.js to libsass, the C interpretation of Sass's famous stylesheet preprocessor. It allows compiling .scss files to css at incredible speed natively and automatically via a connect middleware. 

    It has various features like: 

    • nesting 
    • data variables 
    • mixin functions 
    3What is an alternative for node sass?

    Sass, Webpack, PostCSS, Compass, and Animate.css are considerable, popular alternatives and competitors to node-sass. 

    4Is python required for node-sass?

    Python and C++ are required to compile native modules. Typically, node-sass fetches the binary, and if it is on a supported platform, it downloads the modules without hiccups. 

    5What is the difference between node-sass and sass?

    Node.js is a library that equips binding for Node.js to LibSass, the C version of the famous stylesheet preprocessor, Sass It allows you to compile .scss files to css at incredible speed natively automatically via a connect middleware. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It's translated to well-formatted, standard CSS using the command-line tool or a web-framework plugin. Node-sass and Sass are both open-source tools. 

    6Is Sass and SCSS the same?

    Sass and SCSS are similar and do the same thing, but they are written differently. SCSS is the latest one and is considered better than Sass. 

    7What language is Sass written in?

    Sass is a preprocessor scripting language that is compiled or interpreted into Cascading Style Sheets. Sass is written in SassScript scripting language. Sass consists of two syntaxes. The original syntax is called “the indented syntax,” which uses a syntax similar to Haml. 

    8Is Sass a dev dependency?

    It is required to do a production build and be in the production dependencies list. The project is built afresh for production, so all the packages needed must be built from scratch. A dev dependency like webpack-dev-server is not required for a production build but is used in development (assuming as it is being used).

    Profile

    Rajesh Bhagia

    Blog Author

    Rajesh Bhagia is experienced campaigner in Lamp technologies and has 10 years of experience in Project Management. He has worked in Multinational companies and has handled small to very complex projects single-handedly. He started his career as Junior Programmer and has evolved in different positions including Project Manager of Projects in E-commerce Portals. Currently, he is handling one of the largest project in E-commerce Domain in MNC company which deals in nearly 9.5 million SKU's.

    In his role as Project Manager at MNC company, Rajesh fosters an environment of teamwork and ensures that strategy is clearly defined while overseeing performance and maintaining morale. His strong communication and client service skills enhance his process-driven management philosophy.

    Rajesh is a certified Zend Professional and has developed a flair for implementing PMP Knowledge Areas in daily work schedules. He has well understood the importance of these process and considers that using the knowledge Areas efficiently and correctly can turn projects to success. He also writes articles/blogs on Technology and Management

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon