Can I benefit from Grunt for my Visual Studio based web development?

Standard

Yes you can. Grunt is completely independent of IDEs and texteditors and is a really helpful tool for all kinds of web development in any editor.

Grunt is described as “a node based javascript task runner with which you can automate tasks like minification, compilation, unit testing, linting and more”. You can use it for example when you do not like to be dependent on an asp.net web server doing minification and bundling for you, or you simply like to be able to use tools that are not (yet) supported by the asp.net/Visual Studio ecosystem.

I use it when I create web applications which requires typescript compilations, css and js minifications and separate configurations for development and live deployments. Initially I used WebEssentials for that. But I found that grunt gives me more flexibility and power.

To use Grunt you only need to install Node (from nodejs.org) on your computer. With that in place you tell grunt how to perform it’s magic with the help of two configuration files:

  1. package.config (which contains the npm information about your project and its dependencies)
  2. gruntfile.js (which contains information about your build tasks)

Npm, the Node Package Manager, can help us create a package.config. Just enter npm init from your application folder:

Follow the process in a 5 minutes screen recording here.

Untitled

Answer the questions (just use the default options if you like, it’s not important now) and it will create a package.config for you.

Next we’ll open the project as a web site within Visual Studio:

Untitled

You can edit the information in the file if you like. But we’ll let the npm add some information for us automatically so please save the file before you go on to the next step.

Whenever we use an external tool to edit files for us Visual Studio will notice and ask us if we like to refresh it from file, or keep the version in the editor. I find this a bit annoying and I like it better just when Visual Studio refreshes the files completely automatic (unless I changed them of course). You can change that in the option “Auto-load changes if saved”:

Untitled

Okay. Now let’s add the grunt specific features.

First add grunt itself locally aswell as the task we will use. Go back to the command prompt and install grunt and grunt-ts for typescript compilation:

npm install grunt-ts –save-dev

Grunt-ts has grunt as a dependency so it will install that automatically. (Now dont be surprised by the loads of packages which comes with Grunt. It’s just something you need to get used to when it comes to npm packages.)

Untitled

When Npm is done installing everything you will get a command prompt like below. Also notice that package.config will got a few new lines:

"devDependencies": {
    "grunt": "~0.4.1",
    "grunt-ts": "~0.9.1"
  }

Now we need to add the Grunt Command Line Interface. We install that globally by adding -g so we can use it from any project later:

npm install grunt-cli -g

Now let’s add the gruntfile.js with everything grunt needs to perform the particular tasks for us:

module.exports = function (grunt) {
    "use strict";

    // load all grunt tasks

    grunt.initConfig({

        ts: {
            options: {                    // use to override the default options, See : http://gruntjs.com/configuring-tasks#options
                target: 'es3',            // es3 (default) / or es5
                module: 'amd',       // amd (default), commonjs
                sourcemap: true,          // true  (default) | false
                declaration: false,       // true | false  (default)
                nolib: false,             // true | false (default)
                comments: false           // true | false (default)
            },
            dev: {                          // a particular target   
                src: ["ts/*.ts"], // The source typescript files, See : http://gruntjs.com/configuring-tasks#files                
                watch: 'ts',         // If specified, configures this target to watch the specified director for ts changes and reruns itself.
                out: 'dev',
                options: {                  // override the main options, See : http://gruntjs.com/configuring-tasks#options
                    sourcemap: true
                },
            },
            live: {                          // a particular target   
                src: ["ts/**/*.ts"], // The source typescript files, See : http://gruntjs.com/configuring-tasks#files                
                watch: 'ts',         // If specified, configures this target to watch the specified director for ts changes and reruns itself.
                out: 'scripts/app.js',
                options: {                  // override the main options, See : http://gruntjs.com/configuring-tasks#options
                    sourcemap: false
                },
            },
        },
    });

    grunt.loadNpmTasks("grunt-ts");
    grunt.registerTask("default", ["ts"]);

};

It’s quite a lot of code. But mostly self explanatory. Now lets add some necessary folders:

  • ts : for the typescript code files.
  • scripts : for the compiled javascript. Bundled to one file.
  • dev : for the compiled separate javascript files. With sourcemaps.

Add a basic typescript file in the ts folder.

Now run grunt,

grunt

which will make it compile the typescript file and then keep running to watch for file changes.

Open up the compiled javascript file within Visual Studio and arrange the windows if you like to the javascript file together with the typescript file:

Untitled

Notice it re-compiles and refreshes the javascript file whenever you change the typescript file, or any other typescript file with the ts folder.

The last thing we’ll do is to stop the current grunt process (just by hitting Ctrl+C) and make grunt perform the live task instead:

grunt ts:live

See that we get the compiled file in the scripts folder instead, and without a source map.

Read more about grunt-ts and grunt.

Make grunt do more
After we compile the live version of our script we like to minify it. For that we can use the uglify plugin:

npm install grunt-contrib-uglify --save-dev

*-contrib-* is for plugins that are being maintained by the grunt core team.

Now change and add a few lines at the bottom in the gruntfile:

module.exports = function (grunt) {
    "use strict";
    grunt.initConfig({

        ts: {
            options: {                      // use to override the default options, See : http://gruntjs.com/configuring-tasks#options
                target: 'es3',              // es3 (default) / or es5
                module: 'amd',              // amd (default), commonjs
                sourcemap: true,            // true  (default) | false
                declaration: false,         // true | false  (default)
                nolib: false,               // true | false (default)
                comments: false             // true | false (default)
            },
            dev: {                          // a particular target   
                src: ["ts/**/*.ts"],           // The source typescript files, See : http://gruntjs.com/configuring-tasks#files                
                watch: 'ts',                // If specified, configures this target to watch the specified director for ts changes and reruns itself.
                out: 'dev',
                options: {                  // override the main options, See : http://gruntjs.com/configuring-tasks#options
                    sourcemap: true
                },
            },
            live: {                         // a particular target   
                src: ["ts/**/*.ts"],       // The source typescript files, See : http://gruntjs.com/configuring-tasks#files                
                out: 'scripts/app.js',
                options: {                  // override the main options, See : http://gruntjs.com/configuring-tasks#options
                    sourcemap: false
                },
            },
        },
        uglify: {
            my_target: {
                files: {
                    'scripts/app.min.js': ['scripts/app.js']
                }
            }
        }
    });

    grunt.loadNpmTasks("grunt-ts");
    grunt.loadNpmTasks('grunt-contrib-uglify'); // minifies


    grunt.registerTask("default", ["ts:live"]);
    grunt.registerTask("ts-dev", "Compile all typescript files to dev folder and watch for changes", ["ts:dev"]);
    grunt.registerTask("ts-live-uglify", "Compiles all Typescript files into one and minifies it", ["ts:live", "uglify"]);

};

Notice I have added “uglify”, a few explicit tasks, and descriptions. Now, if we like to compile the typescript for live usage and minify the js we run the command:

grunt ts-live-uglify

If we forget our task names we can list them with their descriptions by running:

grunt -help

Extra

Run MsBuild from grunt grunt-msbuild

Visual Studio addin that adds your gruntfile commands to a context menu GruntLauncher

About these ads

7 thoughts on “Can I benefit from Grunt for my Visual Studio based web development?

  1. I’m a C# developer. I do NOT use Visual Studio though for JavaScript development. You’re much better off as a .NET or any dev using JetBrains WebStorm for the JS stuff, it blows VS away and is what people outside .NET use and totally rocks. So all you are showing here is how to edit js files then open GRUNT externally. It is editor independent, doesn’t matter which editor you use for JS code….yea Grunt works by itself outside anything.

    • Well, I’ve been trying out WebStorm quite a bit, I still prefer Visual Studio every day of the week.

      Many Visual Studio developers hesitate when it comes to tools from outside of the .Net sphere, and they miss great tools like Grunt, hence the article.

  2. Thanks for your marvelous posting! I really enjoyed reading
    it, you may be a great author. I will be sure to bookmark your blog and may come back at some point.

    I want to encourage one to continue your great work, have a nice
    evening!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s