Using Nodejs and grunt to implement automatic compilation of sass

Source: Internet
Author: User
Tags add command line end functions implement interface version install node

Article Introduction: I heard earlier that Nodejs and grunt are very powerful, especially used to build automated front-end development, but also powerful and incomparable. But has been due to their own mastery of the technology is limited, dare not in-depth, and never go down. Recently in the beginning of learning sass, but also slowly contact this aspect of things. In order to better enable the SASS project to automate the compilation, intends to use Nodejs and grunt to try.

I heard earlier that Nodejs and grunt are very powerful, especially used to build automated front-end development, but also powerful and incomparable. But has been due to their own mastery of the technology is limited, dare not in-depth, and never go down. Recently in the beginning of learning SASS, but also slowly contact this aspect of things. In order to better enable the SASS project to automate the compilation, intends to use Nodejs and grunt to try.

Sass's compilation of the topic, in the "Sass compilation " has been introduced, the method is described in the Ruby environment, the use of SASS commands with its various parameters to achieve SASS compilation. So today we have changed a way, using Nodejs and grunt to achieve sass automatic compilation.

Brief

As a developer (a lot of people don't think that the front-end people are not developers, here for a while), they want to be lazy in actual development. Avoid some repetitive, meaningless work, of course, also want to use some tools to improve their development efficiency, freeing up more time to do their favorite things.

In fact, there are many new tools that can help us accelerate the development and simplification of our workflows. But as a front-end person, these tools are often daunting. This time I am also in order to be able to better the whole meeting sass, therefore also the bite the bullet to begin to contact these new dongdong. So today we're just going to try to cooperate with Nodejs, grunt and sass to realize the automation compilation of SASS Project.

Nodejs is a server-side JavaScript interpreter that will change the concept of how the server should work. Its goal is to help programmers build highly scalable applications and write connection codes that handle tens of thousands of simultaneous connections to one (only one) physical machine.

Grunt is an application build, task management tool. It can realize the production automation, avoid Dali tedious monotonous repetitive work. The goal is to automate and reduce the repetitive work you do. Once you have configured a grunt task management, it can help you reduce a lot of repetitive work, using the configuration and reducing the likelihood of errors.

SASS is a CSS (cascading style sheet) of the syntax of an extension, but also the most mature of a CSS preprocessor language, it can use variables, constants, nesting, mixing, functions and other functions, can be more effective and flexible to write CSS.

Where Grunt is a JavaScript command line player, and sass is a CSS preprocessor program, the combination of both is a very powerful automation tool. You can quickly compile sass into CSS.

Environmental Requirements

Before we begin, we need to change some of the previous concepts. For a front-end staff, the idea in everyone's mind is how to convert the PSD map into HTML and CSS, plus javasctrip handle some interactive effects, complete the browser compatibility is OK. So, when you get the design, there's an editor (a little bit more powerful that will go with the IDE) to start working. However, we should take a step ahead of the strong future, suitable for some automation functions, help us solve some repetitive work.

If you've ever known sass, you'd know that Sass needs Ruby, and grunt can't be separated from Nodejs NPM. So before you use grunt and sass, you need to install something, that is, the environmental requirements:

    • Ruby Environment
    • Sass Installation
    • Nodejs Environment
    • Grunt Installation
installing Ruby and Sass

First we need to install Ruby and SASSon the computer. If you're using a Mac, you don't need to install Ruby. If you are using the window system, you need to install Ruby.

When you make sure that your computer has the Ruby installed, you can run it at your command terminal:

 

Or

 

You can also use:

 

Installs the pre-release version of Sass. This allows you to use the SASS command globally on your computer.

For the installation of sass and some basic operations, you can refer to: "Sass Compilation " and "Sass Debugging " related introduction.

Install Nodejs

Since the use of grunt requires NODEJS support, we need to make sure that our computer has Nodejs installed. Once installed, see if the node command can be executed at the command line, and if so, the installation is successful.

Simple installation is to go directly to the Nodejs website to download the installation of the system required to install the package.

If you want to challenge some of the more interesting installation methods, you can use the command to install. Interested students can take a look at the following tutorial:

    • How to Install Node.js
    • Installing and running Node.js on Mac OS X
    • Setting up Node.js and NPM on Mac OS X
    • Installing Node.js, NPM, and Redis on Mac OS X
Install grunt

It's easy to start using grunt . If you are using this stuff for the first time, you need to install it first. The detailed installation process can refer to:Mac OS x installation grunt and windows under install. In this article, the main in the Mac OS x environment to do a simple introduction.

Before installing grunt, first make sure your computer is Nodejs. At the time of writing this tutorial, My Computer installation is:

 

The NPM version is:

 

The next step to install grunt is the v0.4.1 version. Note: If you have previously installed grunt other versions of your computer, you will need to uninstall the previous version before you can install the latest version of Grunt.

Install the grunt command line interface (CLI)

Before installing grunt.js, you need to first install the Grunt command-line interface. The installation method is also very simple, open your command terminal, on the command line, enter:

 

To install this, you may not be able to install it successfully, as shown in the following illustration:

When you see the command terminal prompts you:

 

At this point, you need to add sudo in front of the command above:

 

Next, enter your root password and the command will be installed automatically. After the final installation, the relevant information is displayed, as shown in the following figure:

The above command installs the Grunt command panel under your system's path, allowing the grunt to run on all directories. That is to say, this is a global installation.

This grunt command panel is installed successfully, you can also start using grunt, if you want to uninstall grunt, you can enter directly in your terminal:

 
Create a project 

Environment creation configuration Well, let's create a test project to facilitate subsequent content continuation. I generally like to put items in the Sites directory, for example, here, I created a "Gruntsass" project, and put it under the sites:

 

At the same time I like to place grunt related files in the _build directory, so you need to create a _build directory in the Gruntsass directory to place Grunt project management files:

 

After you have created the project, you need to create the Package.json and gruntfile.js two files at the root of the project:

 

Then copy and paste the following piece of code into the project package management file Package.json:

{   ' name ': ' Gruntsass ', '     version ': ' 0.0.1 ',     ' devdependencies ': {  
       "Grunt": "0.4.1",         
        "Grunt-contrib-sass": "0.4.0"     

Then copy and paste the following code into the Gruntfile.js file:

Module.exports = function (grunt) {      //Project configuration.
     Grunt.initconfig ({          //read the Package.json (optional)
         Pkg:grunt.file.readJSON ("Package.json"),
          Metadata.         Meta: {
             
            
            Deploypath: ". /assets/css/"
         },          
                
                
         Task configuration.
         Sass: {
             Dist: {
                 
                    "<%= meta.deploypath%>style.css": "<%= meta.srcpath%>style.scss"
                 
                
                    
                }
             }
         },
         
            Scripts: {  
               
                    
                ],
                 tasks: ["sass"]
             }
         }     });
      These plugins provide necessary tasks.
     
    Grunt.loadnpmtasks ("Grunt-contrib-watch");      The Default task.     

Run at this time under Sites/_build:

 

will see the terminal running a series of Dongdong, as to run is what, I also do not understand, as the following picture shows:

After you run the terminal command, you will automatically create a node_modules directory in your project that contains some module feature files:

Then run in the terminal:

 

Command Terminal display information:

 

As soon as you modify your sass file, the terminal provides monitoring information and translates your sass code at the same time:

>> File ". /assets/sass/style.scss "changed. Running "Sass:dist" (sass) task done  , without errors.
 

This opens the Grunt monitoring sass. Also completes our grunt translation sass function.

Sass Translation CSS

With the previous introduction, we can now manage and translate sass projects through grunt in our projects, and now we go back to the simple understanding of some key points.

Once you are running in a project by using the previous description:

 

If the above command runs successfully, the grunt JS packages will be added as a node_modules directory and placed under your installation directory, which is under Sites/gruntsass/_build. So sass can be translated into CSS. If you look at the Gruntfile.js file, you can see:

Sass: {
   Dist: {
     
      "<%= meta.deploypath%>style.css": "<%= meta.srcpath%>style.scss"
     },
     Options: {
        Sourcemap: "True"     }   

Just such a piece of code, can let style.scss and through @import import in. scss translates into style.css. Of course, we need to run in the _build directory:

 

The prompt is displayed on the command line:

Running "Sass:dist" (SASS) Task  

In fact, we can recall that the grunt command here is equivalent to the SASS command.

Of course grunt command can make. Scss translate into. css, mainly because people we set the default task in Gruntfile.js to:

 
SASS Watch Command 

--watch parameters are configured in the SASS command, we can monitor the. Scss from time to time, and once any changes have been made, they are automatically translated into the corresponding. css. This makes our job easier. In fact, we can implement similar functions in grunt.

In the _build directory of the project, we created a Package.json file in which you can see a code similar to the following:

{   "name": "Test-sass-to-css",   "version": "0.1.0",   
    "Grunt": "~0.4.1",     "Grunt-contrib-sass": "*"   

We only need to add "grunt-contrib-watch" on this basis: "*" added to the Package.json file:

{     "name": "Test-sass-to-css",     "version": "0.1.0",
     "Devdependencies": {"         grunt": "~0.4.1",
         "Grunt-contrib-sass": "*",
         "Grunt-contrib-watch": "*"     

For the example used in this tutorial, the contents of the Package.json file are similar to the following:

{   
    "Version": "0.0.1",
     "Devdependencies": {
         "Grunt": "0.4.1",
         "Grunt-contrib-watch": "0.4.3",
         "Grunt-contrib-sass": "0.4.0"     

Install the watch package to the _bluid directory by using the following command:

 

It's basically done. If you create this project in this way, I am sure you will be able to create the next project very quickly. But don't forget, you also need to include in the Gruntfile.js file:

 
   Scripts: {
       Files: [
         "<%= Meta.srcpath%>/**/*.scss"
       ],       tasks: ["sass"]    
 

This time at the command terminal run:

 

After running, you receive a prompt message:

 

If you modify any. scss file, it will be monitored and automatically translated:

>> File ". /assets/sass/style.scss "changed.  
Running "Sass:dist" (SASS) Task  

In fact, here Grunt watch want to be sass--watch.

If you follow the above content to come here, I think you can also smoothly use Nodejs+grunt to handle SASS Project translation. Then every project you can do so, if you are familiar with the grunt, he can also help you build other automation, a word, is powerful let you frighten a lot of small students.

Extended Reading
    • Getting Started with grunt and Sass
    • Compile SASS files into one CSS file grunt JS Tutorial
    • Get up and Running with Grunt.js
    • Import a Whole Directory with Sass (Using grunt)
    • Faster Sass debugging and style iteration with source maps, Chrome Web Developer Tools and Grunt


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.