Saturday, May 28, 2016

Understanding npm and Grunt

npm
Javascript is not a language where your code gets compiled. So like .NET you can not just build the code and add dependencies and resolve it easily. In case of javascript, we need to add dependencies manually and need to make sure that the final HTML page do have reference to all these dependencies.
This is a very common step which everyone will have to do. So the idea came to automate all these steps and that is where the package manager and Grunt comes in.
If you have idea of .NET, there is nuget package manager. It helps us load the dependencies using nuget packages. Similarly in Javascript also, there are packages available to be reused. We can download these packages using node package manager(npm). In order to use the npm, we need to install it.
Detail about installation can be found on the official npm website.

package.json
In .NET packages we have package.config file which has all the detail about the package installed. In Javascript we have package.json available which help us configure the packages required.
Package.json has all the detail of your application, and its dependencies.
just execute "npm init" to create package.json file(we can create it manually as well).
Sample package.json –
{
    "name": "dummy-tutorial",
    "version": "1.0.0",
    "private": true,
    "license": "see LICENSE file",
    "description": "Dummy package.",   
    "dependencies": {
    },
    "devDependencies": {      
    } 
}
Dependencies – Mention the dependencies required in the project and will be required in actual production. Dependencies mentioned here become part of your bundle that you will be  deploying.
devDependencies – Mention those dependencies which are required only for local development.
“npm install” – command will create node_module folder having all the packages mentioned in the package.json

Grunt – Grunt is a task running tool. You can configure multiple tasks one after another to be executed. Say you want to process a js file written with ES6 code into ES5 and then want to concat multiple of these files in to 1, then you can configure these tasks to be executed one after another.
Grunt is also a package which you need to install.
There is a Grunt.js file which is used by Grunt to understand the required module, their dependencies and the task that need to be executed.
Grunt file has 3 important parts –
1-   Initconfig
2-   Loadnpmtasks
3-   Register task
Sample Grunt.js file - 
module.exports = function (grunt) {
    grunt.initConfig({
       // Tasks configuration go here
    });
                //load tasks
    grunt.loadNpmTasks(/*task name*/);
                //optionally create custom tasks
    grunt.registerTask("default", [ /*array of tasks*/]);   
};

No comments:

Post a Comment