Posts tagged with "JavaScript"

Add Grunt and ESLint to a MVC Project

This is part two of getting started with ESLint using Grunt where I will show you how to configure ESLint to analyse a MVC .NET Project. In part one I set-up our environment with node.js, Grunt-cli and finally Grunt for our project, but you couldn’t do much with it.

In this post, I’ll install ESLint, disable all the default ESLint rules, enable one specific some rule and exclude some files from analysis.

Add Grunt and ESLint to a MVC Project
Add Grunt and ESLint to a MVC Project

To recap, I have a new ASP.NET MVC project in c:\myproject\WebApplication1 that also contains a package.json and Gruntfile.js:

C:\myproject\WebApplication1> dir -name
node_modules
packages
WebApplication1
Gruntfile.js
package.json
WebApplication1.sln
C:\myproject\WebApplication1>

Let’s get started.

Step 1 – Install ESLint and Grunt-ESLint

Like last time, npm makes installing things trivial. First, install ESLint:

npm install --save-dev eslint

Once that’s completed, install the ESLint grunt integration:

npm install --save-dev grunt-eslint

And finally install load-grunt-tasks, which saves a bit of typing in a minute:

npm install --save-dev load-grunt-tasks

Step 2 – Configure ESLint

eslint.json

To make our lives easier to change the configuration of ESLint, we’re going to use an eslint.json file. As you can probably tell from the name, it’s a text file containing some json that ESLint parses. The ESLint documentation is pretty good at explaining what all the options are, so I won’t do that here, but for now just create one containing the following:

{
    "env": {
        "browser": true,
    },
	"globals": {
        "$": true,
    },
	"rules": {
        no-undef: 1,
    }
}

This ensures the browser and jQuery ($) variables are recognised by ESLint so they don’t throw false positive. It also enables a single rule “no-undef – disallow use of undeclared variables unless mentioned in a /*global */ block”.

As you will see in a minute, I personally like to disable **all ** the rules, only enabling the ones I explicitly want to use. That’s personal preference, as on legacy systems you can end up with a lot of issues to address which can seem overwhelming.

.eslintignore

The next file that we need to create is .eslintignore. As the name suggests, this is an easy way of telling ESLint to ignore certain files and directories. Again I refer you to the documentation for more details, but for now, create an .eslintignore file containing:

# ignore everything in the packages folders
**/packages

# ignore everything in Scripts except files beginning with "myapp"
**/Scripts
!**/Scripts/myapp*

This tells ESLint to ignore all files inside the packages directory, i.e. anything you’ve got from nuget. The last two lines ensures all files except those following your applications naming convention – you have a naming convention right? – are also ignored, i.e. jquery..min.js etc.

Finally, all that’s left is to configure Grunt to run ESLint.

Step 3 – Configure Grunt to use ESLint

Before explaining the syntax, please edit your Gruntfile.js file to contain:

module.exports = function(grunt) {
	# section 1 - require modules
	require('load-grunt-tasks')(grunt);

	# section 2 - configure grunt
	grunt.initConfig({
		eslint: {
			options: {
				config: 'eslint.json',
				reset: true
			},
			target: ['WebApplication1/**/*.js']
		}
	});

	# section 3 - register grunt tasks
	grunt.registerTask('default', ['eslint']);

};

The more you play with Grunt the more familiar this will be, but it’s basically made up of 3 sections. Section one lists any requirements (“require” calls), section 2 is where you initialize Grunt and section 3 where you register tasks.

In this instance, I’m configuring a single “target” called “eslint” and telling it to use the eslint.json file, turn off all the rules (reset: true) and to search for all JavaScript files inside the “target”.

Finally I register the “eslint” target to be the default task. This simply means I can execute “grunt” instead of “grunt eslint”.

Which if I do that, I get:

C:\myproject\WebApplication1> grunt
Running "eslint:target" (eslint) task

WebApplication1/Scripts/_references.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/bootstrap.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/bootstrap.min.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/jquery-1.10.2.intellisense.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/jquery-1.10.2.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/jquery-1.10.2.min.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/jquery.validate-vsdoc.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/jquery.validate.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/jquery.validate.min.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/jquery.validate.unobtrusive.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/jquery.validate.unobtrusive.min.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/modernizr-2.6.2.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/respond.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

WebApplication1/Scripts/respond.min.js
  0:0  warning  File ignored because of your .eslintignore file. Use --no-ignore to override

? 14 problems (0 errors, 14 warnings)

And that's it! ESLint is now analysing the JavaScript files in my MVC project.

Step 4 – Next Steps

If you’ve got this far, you’re set to go. You will definitely want to edit the rules you’re using, but I’ll leave that up to you.

Please leave a comment below or catch me on twitter if you’re having any problems.

Getting Started with ESLint using Grunt

Getting Started with ESLint using Grunt
Getting Started with ESLint using Grunt

I recently had the chance to add ESLint to our workflow. I considered using it standalone, but as Grunt is becoming a first class citizen in Visual Studio 2015, I wanted to get more familiar with it now.

This is the first of a two part guide to getting started with ESLint using grunt. I’ll also help you understand how to enable other ESLint rules as well as include/exclude files from analysis. I’m going assume you have little to no experience of node.js, Grunt or ESLint and are running windows. In this post I’ll cover the setting up of your environment and next time we’ll go about installing and configuring ESLint to work on a ASP.NET MVC project. This guide could also be used to add ESLint any project that contains JavaScript or even a different operating system, but I haven’t tested that, so won’t make any promises.

Once we’ve finished, you should be able to type “grunt” from a command prompt and ESLint will analyse your JavaScript, so let’s get started.

Step 1 – Install Node.js

Installing Node.js, which includes npm (node package manager – think nuget for node), is as simple as going to the Node.js homepage, clicking the “Install” button and executing the .msi file that downloads.

Once the install has finished, open a command prompt and type “npm”. If you’re presented something like this, you’re good to go. If you have any problems, let me know in the comments.

Usage: npm <command>

where <command> is one of:
    add-user, adduser, apihelp, author, bin, bugs, c, cache,
    completion, config, ddp, dedupe, deprecate, docs, edit,
    explore, faq, find, find-dupes, get, help, help-search,
    home, i, info, init, install, isntall, issues, la, link,
    list, ll, ln, login, ls, outdated, owner, pack, prefix,
    prune, publish, r, rb, rebuild, remove, repo, restart, rm,
    root, run-script, s, se, search, set, show, shrinkwrap,
    star, stars, start, stop, submodule, t, tag, test, tst, un,
    uninstall, unlink, unpublish, unstar, up, update, v,
    version, view, whoami

npm <cmd> -h     quick help on <cmd>
npm -l           display full usage info
npm faq          commonly asked questions
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
    C:\Users\Matthew\.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

Step 2 – Install the Grunt Command Line tools (grunt-cli) globally

Getting Started with ESLint using Grunt
Getting Started with ESLint using Grunt

The next step is to install the Grunt Command Line tools globally using npm. Thankfully that’s as simple as typing the following in a command prompt:

npm install -g grunt-cli

Step 3 – Prepare your project for Grunt

For grunt to run on our project, you need a “package.json” file and a “gruntfile.js” file.

package.json

You could create this file by hand, but npm can talk you through the process, so in the root of your project type:

PS C:\myproject> npm init

You will get asked a series of questions, which if you don’t know the answer to, just hit enter to skip it. The file is editable, so can be changed later if need be. Depending on what you answer, you’ll end up with a package.json file containing:

{
  "name": "npminit",
  "version": "1.0.0",
  "description": "Description",
  "main": "index.js",
  "scripts": {
    "test": "test"
  },
  "author": "Matt Dufeu",
  "license": "ISC"
}

This file will also be automatically updated by npm when we start installing other packages, as we’ll see in step 4.

Gruntfile.js

Gruntfile.js is similar to a makefile (showing my age) and is used by grunt to see what to do when you issue grunt commands. To get started, create a file that contains:

module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON("package.json")
  });
};

Don’t worry about what this means at the moment, we’ll be modifying this later.

Step 4 – Install Grunt locally

The final setup step is to install Grunt locally. Again, npm comes to the rescue, but this time we specify “–save-dev”.

PS C:\myproject> npm install grunt --save-dev

This will do two things; firstly, it will create a folder called “nodemodules” to your project. This is basically the folder npm stores all the packages for _this project, so think of it as a libraries folder.

Secondly, it will install Grunt as a dependency to your project. Take a look at your Gruntfile.js now and you will see a new section like this:

...
"devDependencies": {
  "grunt": "^0.4.5"
}
....

“devDependencies” simply lists the packages the project is dependent upon and their version number. It gives you the option of moving the project to a different location without the node_modules folder and typing “npm install” to get npm to download the required dependencies.

Step 5 – Verify it’s working

To check that’s working as expected, simply execute grunt, and you should see the below. It’s basically saying “there’s nothing to do”, but at this stage that’s expected.

PS C:\myproject> grunt
Warning: Task "default" not found. Use --force to continue.

Aborted due to warnings.
PS C:\myproject>

Summary

We’ve installed node.js, npm, the Grunt command line tools and setup our project.json and Gruntfile.js files. We’re now ready to start adding ESLint to our project, so next time, I’ll be adding ESLint, showing you how to enable/disable ESLint rules and finally exclude certain files from analysis.

Please leave a comment below or catch me on twitter if you’re having any problems.

[Update: part 2 is now available.]

All categories