Grunt compiling Sass&compass and compressing JS workflow

Source: Internet
Author: User
Tags package json

Original:Grunt workflow for compiling Sass & Compass and minifying Javascript

Previously, we installed NODE,NPM and grunt also included a Package.json file created and a gruntfile file. In this exciting article, we will fill everything, and you will see how amazing grunt is, and experience his awe-inspiring power, just as satisfying as a lazy bath in the warm sunshine.

If you have not installed NODE,NPM and grunt then you need to install these things (really not difficult and not afraid) and then continue to look down.

Here are some of the things we want grunt to do for us:

1. Monitor the HTML,JS and sass files that we have changed in the project

2. Compiling Sass&compass

3. Compress and connect JS files

So let's go on down.

What is grunt?

Grunt is a JavaScript task runner (JavaScript Tasks runner), which is written with JavaScript (using node Js) to run tasks. Grunt uses two files--a Package.json (tells Grunt all the dependencies he needs) and a gruntfile file. If you read the previous article, you may already have these two files in your project folder. If not, go to the GitHub repository to download or fork.

Package JSON file

This Package.json file is a npm thing. I understand (perhaps not enough) that in your project it is the metadata that stores all of the node dependencies. This article is a good overview of Pasckge.json.

Install a Grunt plugin

Grunt runs tasks with automation plugins. We need a few plugins to implement the 5 goals listed at the top of the article. One to listen to all the changes, one to run the compass, one to connect/compress our JS file, but also need to do a real-time reload page multi-device things.

came to the command line. First we need to browse the project

With this command:

$ CD Path/to/my/project/folder

If you follow the path of your project directly behind that CD command (into your project directory), you can now install the first plugin using this command:grunt-contrib-watch

$ NPM Install Grunt-contrib-watch--save-dev

This command will output some machine language that makes you feel uncomfortable, but you can leave it out of your control. When the installation is complete, go to see your Package.json file. It should have an update that contains Grunt-contrib-watch dependencies for this small piece of text:

//  ...    " Devdependencies ": {     " grunt ":" ~0.4.1 ",     " Grunt-contrib-watch ":" ~0.5.0 "   }}

Now go back to the command line and repeat the following command to install the two plugins:

$ npm Install grunt-contrib-compass--save-Dev $ npm Install grunt-contrib-uglify--save-dev

A little lucky, now that you've got all the plugins you need for the project. Your Package.json file should also list the dependencies (and possibly more) of all these plugins.

Gruntfile file

This gruntfile file looks a little like this:

function    //  Project configuration.     pkg:grunt.file.readJSON (' Package.json '  //  config (some configurations) =========   ==========================///DEPENDENT PLUGINS (dependent plug-in)         ======= ==================/   grunt.loadnpmtasks ();    // Tasks (Task) =====================================/    Grunt.registertask (' Default ', []); };

This gruntfile is divided into 3 main sections:

    1. Dependencies (dependent plug-in)
    2. Tasks (Task running)
    3. Task Configuration (Assignment)

Set these configurations and choose to use it as the first part of your gruntfile, introduce the plug-in as the second part, and then tell Grunt to run these plugins, as per the one you configured. Complete these tasks by entering the "grunt" command at the command line, or enter "Grunt <task-name>" to run the specified task or sub-task. (<task-name> is the name of the task you want to run, such as you want to compress the CSS now, and its task is called "Cssmin", and you enter "Grunt Cssmin" at the command line)

Now let the first part of Gruntfile contain the plugin we rely on, find the " grunt.loadNpmTasks(); " line, copy the entire line and paste it 3 times, and that should look like this:

   // ...    // DEPENDENT PLUGINS =========================/   Grunt.loadnpmtasks (   ) ;          //  ... };

Enclose the plugin name in quotation marks and add it to parentheses, like this

//  ...    // DEPENDENT PLUGINS =========================/   grunt.loadnpmtasks (" grunt-contrib-watch );
Grunt.loadnpmtasks ('grunt-contrib-compass
Grunt.loadnpmtasks ('grunt-contrib-compass

// ... };

Next, configure the watch task to copy and paste the configuration below the comment line:

// CONFIGURATION =============================/ Watch: {    compass: {      files: [' **/*.{ Scss,sass} '],      tasks: [' Compass:dev ']    },    js: {      files: [' * */*.js '],      tasks: [' uglify '    }  },//  ...   };

Above we created a watch task whose subtasks are compass (referring to watch:compass) and JS (WATCH:JS). Configure the Watch:compass task to listen for files ending with a. scss or. sass suffix name. If these files are modified, the Watch:compass task will perform the "Compass:dev" task. Configure the JS task to listen to the JS file, if the JS file is modified then it will run the "uglify" task.

Lets set up the Compass task. After the last closing bracket and comma of the watch task (follow the indentation) add the following:

Now let's configure the Compass task. Add the following code after the last closing brace and comma of the watch task (the same shrink):

Compass: {   dev:{       options: {                         sassdir: [' Styles/sass '],           Cssdir: [' styles/css '],           Environment: ' Development '       }   } ,

Now we have the Compass task configured, and a subtask called Dev (compass:dev), indicating the directory of the SASS directory and output CSS, the configuration environment is ' development ' (development environment). When we compile, we also use the default configuration in the development environment (like the default to keep the expanded format output CSS, add line annotations by default, etc.).

Now we would have just set up a compass task. This selection block is enclosed in parentheses in the comass:{}. But we want to make COMAPSS a little more flexible than it is now. Then configure a separate production (production environment) task, and edit the compass as follows:

        // ... dev options here Options:       {               sassdir: [' Styles/sass '                          Cssdir: [' styles/css '          Environment: ' Production '      }   } ,

Now we can invoke the Compass:prod task, compile the Sass file and then output the style in compressed (compressed) format, ready for deployment.

Configure our uglify task below to connect/compress JS files. After the COMAPSS task, add the following code:

                  ' Js/min/main.min.js'          js/libs/jquery.js ',                                }, },

When we run this task, Uglify will get all the files listed in square brackets and then compress them together. If we have some HTML build process (for example, using a static site builder), in the development environment we might include the complete script and then run the ZIP code above to separate our prod tasks-just as we did on the compass task above.

This build process really makes the grunt shine like Codekit. You can run custom dev tasks and build the production environment you need, just by grunt prod commands. You can even use the same as grunt git deployment or grunt FTP deployment and send your site to the server as part of building a production environment. I'm off the topic ....

Default Task

We need to compile our CSS and JS when we start grunt. We also want to run our watch missions. To do this, we use the default task to trigger. Find a line like the following in your sister's gruntfile:

Grunt.registertask (' Default ', []);

Any tasks we want to run when we enter Grunt need to go between the square brackets. So add ‘compass:dev‘ , ‘uglify‘ , ‘watch‘ between the brackets (with quotes and comma seperated).

When we enter grunt any task that you want to run needs to be in this square bracket. So add ‘compass:dev‘ , ‘uglify‘ , ‘watch‘ in parentheses (separated by quotation marks and commas).

Anyway, let's try these things that we've done so far. Now go to the command line (make sure in your project directory), enter grunt after pressing ENTER, and then you will see:

Running "Watch" task waiting ... Warning:emfile, too many open files

Over and over and over again if you like you can try to do this and then press CTRL + C to quit the process.

The reason is that we are listening to all the JS files in the project. If you go to see the Node_modules folder, this is when we install all the node plugins automatically added, here you will see many folders and a lot of JavaScript files. We need more details about what JS file to listen to. To update your watch task:

            Files: [' **/*.{ Scss,sass} '      tasks: [' Compass:dev '                //  <==Change here       tasks: [' uglify '   }},

By adding the JS folder, we can ensure Grunt isn ' t wasting time and energy watching millions of JS files (unless Millions of JS files in your JS folder-i don ' t recommend a million JavaScript files in your project)

Try running grunt now by going to your command line and entering "grunt".

By adding JS folder, we can guarantee that grunt does not waste time and effort to listen to tens of thousands of JS files (unless you really have thousands of JS files in your project-I also do not recommend you project you have thousands of JS files)

Now, enter grunt in the command line to try running it.

Running "Compass:dev" (Compass) Task unchanged styles/sass/style.scss compilation took 0. 001s   Running "Uglify:all" (uglify) Task File "Js/min/main.min.js" created.  Running "Watch" task waiting ...

Brush Brushes! These feedback information is very good for each task description. Now what is it waiting for? Oh, it's waiting to compile the changed file. So let's go fix a scss file and save it. Now take a look at this command line and you can see the following:

Running "Watch"    >> File "styles/sass/style.scss"   Running "Compass:dev "     Remove. sass-cache/      Remove styles/css/style.css      Create STYLES/CSS/STYLE.CSS (0  compilation took 0. 01s done , without errors.  in 1.305s at Mon Sep 22:31:48 gmt+0100 (BST)-Waiting ...

Now you can clearly see the changes in your CSS file! Really good!!!

Detach Grunt Task

The last thing we'll set up is a Non-default task.

Now you can run any task in grunt by typing "grunt taskname:subtask" in the command line. For example to run our Compass:prod task, we would enter:

Finally, we will build a non-default task.

Now, in grunt you can run any task by entering the grunt taskname:subtask command. For example, to run the Compass:prod task, we enter:

$ grunt Compass:prod

This is nice, but if you have a JS file that needs to be compiled for a production environment or deployed to FTP like the one above, and you want to run it at the same time, it can be very difficult to enter commands on the terminal.

Under the default task line, enter the following code:

// PROD BUILD grunt.registertask (' PROD ', [' Compass:dev ']);

Here we create a custom task prod and also add a run task when it is executed (our Compass:prod task). Use the same rules as the default task to add other tasks, from left to right in the order you want to run, separated by quotation marks and commas.

Now let's go and modify the Sass file and run this command at the terminal:

$ grunt Prod

If all starts to work, it will start compiling again and compressing the CSS file to a single line

Automated work = Cocktail

And what we've done. Actually build all just a little bit of work, but most of the things have been done and don't need a lot of time next time. Simply extend the gruntfile and Package.json files to meet the needs of your next project

Grunt compiling Sass&compass and compressing JS workflow

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.