Windows Store apps

Using Grunt to compile .less in Windows Store apps

I was playing with Grunt. Grunt is a JavaScript task runner. It automates a lot of repetitive tasks like minification, unittesting, linting and more. I’ve used it to compile templates and compile .less files to .css. In this tutorial I’ll show you how to do the latter.

Before we dive into Grunt you need Node.js. Just go to http://nodejs.org and install it. NodeJS can serve websites, but can also run tools. Like Grunt. Node.js uses a package manager (a bit like NuGet), npm. You’ll be using npm a lot when using Node.js.

Getting started

First let’s create a new project in Visual Studio, a Windows Store app with JavaScript of course. (Although everything in this tutorial can be used in Windows Phone apps and universal apps too, as long as you use JavaScript). I named mine GruntLessApp.

After creating the project start the Node.js command prompt. This should be somewhere in your start menu. And navigate to the project folder of the project you just created.

Now before we can use Grunt we need to install it. In order to get started first install the command line interface, grunt-cli.

Type the following in the command prompt: npm install grunt-cli -g

This tells the node.js package manager, npm, to install grunt-cli globally so it can be accessed from every location.

Grunt uses 2 configuration files. Packages.json contains all packages your project is dependent on. The other one is gruntfile.js. Creating packages.json can be done by typing: npm init

And follow the instructions.

So, now it’s finally time to install Grunt itself…

Grunt

Just type: npm install grunt –save-dev

This will install Grunt and save the dependency to the packages.json file. If you save this file in your source control others can use this to install the same dependencies (by typing npm install). I personally just include these files in my project in Visual Studio and set the Package Action to none. This way I can easily edit the files in Visual Studio and store in under source control.

To get Grunt to compile your .less files you’ll have to install a task for it.

Type: npm install grunt-contrib-less –save-dev

Your packages.json file will look something like this now:

{
  "name": "GruntLessApp",
  "version": "0.0.0",
  "description": "demo application for grunt and less",
  "main": "js\\default.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "BSD-2-Clause",
  "devDependencies": {
    "grunt": "~0.4.4",
    "grunt-contrib-less": "~0.11.0"
  }
}

 

Last thing we’ll need to do is setting up the gruntfile.js file. If you like some samples of this file, have a look at the Grunt site. This file is not created automatically in this case, but you’ll can just add a .js file in visual studio in the root of your project. Be sure to set the package action to none so the file doesn’t get included in the package when you publish the app.

The gruntfile.js file is build using a few parts. The first line is the definition of a functions. This part is the same for every gruntfile.js.

module.exports = function(grunt) {
  // Do grunt-related things in here
};

 

Inside this function you’ll have to tell Grunt the configuration for the tasks to execute. This is done by passing an object to grunt.initConfig(); like so:

grunt.initConfig({
        less: {
            development: {
                options: {
                    paths: ["css"]
                },
                files: {
                    "css/default.css": ["css/*.less"]
                }
            }
        }
    });

 

Let’s go over this. The less object in line to tells Grunt we’re talking about the configuration for the less tasks. Next, on line 3, we’ve named this configuration. You can have multiple configurations for various situations. On line 4 the actual the options of the less task are specified. In this case we’ll tell the task it should use the “css” folder as a base for the @import less function. The files section on line 7 tells the task to combine the *.less files into ‘default.css’.

grunt.loadNpmTasks('grunt-contrib-less');
grunt.registerTask('default', ['less:development']);

 

The last two lines tell Grunt to load the less contrib package and register the ‘less’ task as the default. If your gruntfile.js grows over time with more and more tasks you’ll have more of these. Probably in various forms, for development and publishing for example.

To try this out, rename your default.css to default.less and change the contents to something like:

@bgColor: #333333;
@fgColor: red;

body {
    background-color: @bgColor;
}

#content{
    border: 1px solid darken(@fgColor, 20%);

    .item{
        color:@fgColor;
    }
}

 

Now go back to your command prompt and type: grunt

To get you project to use the “new” css file, include it in your project. Set the package action of the .less file to none to exclude it from being packaged.

Automate

There are a few ways to get this process a bit more automated. Grunt is all about removing repetitive tasks and typing a command in a prompt after every change is pretty repetitive.

One way is to use the grunt-contrib-watch package. Using this package will enable you to have the command running continuously and monitor folders and files for changes. When a change happens a series of tasks can be run. Added the task is pretty straight forward. It’s basically the same as described above with the less-task.

In the case of .less files I prefer another method. Because the installation of Node.js has added the path of the npm packages to the “PATH” environment variable, the packages installed with the –g flag can be used everywhere. So let’s add it as a prebuild task to our project.

For this we have to edit the project file. By unloading the project you can edit this inside Visual Studio. Right click the project file in the solution folder and select Unload Project.

Right click the project again, and select Edit GrunLessApp.jsproj.

At the very bottom of the xml, but right before the closing </project> tag, add the following:

<Target Name="BeforeBuild">
    <Exec Command="grunt" />
</Target>

This will do exactly as it says, before the build, execute the command grunt.

To try it out we’ll have to reload the project. To do this, close the file, right click the project in the solution explorer and hit Reload Project.

From now on, on every build, grunt will be executed and help you compile your .less files to .css.

Wrap-up

And that’s it.

A few links to read more about what was discussed in the tutorial:

One comment

Leave a Reply

Seo wordpress plugin by www.seowizard.org.
%d bloggers like this: