Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use JSHint and Browserify together?

I'm attempting to build a project using Angular and Browserify. My controllers.js file looks like this...

'use strict';

module.exports.testController = function($scope){
    $scope.message = 'Controller 1';
    console.log( 'hello' );
};

As you may expect, that generates three linting errors.

  • Use the function form of Strict
  • 'module' is not defined
  • 'console' is not defined

I did find a bit of a solution here that enables JSHint to process Node.js files by putting jslint node: true at the top of the file like this

   /*jslint node: true */
   'use strict';

    module.exports.testController = function($scope){
        $scope.message = 'Controller 1';
        console.log( 'hello' );
    };

However, that obviously fixes too much; 'console.log(...)' should still be undefined.

Does anyone know how to use JSHint with Browserify?

like image 973
gargantuan Avatar asked Jan 28 '14 23:01

gargantuan


People also ask

What is JSHint node?

JSHint is a program that flags suspicious usage in programs written in JavaScript. The core project consists of a library itself as well as a CLI program distributed as a Node module.


2 Answers

As of version 2.5.3 JSHint supports the browserify flag.

Like all flags you can use it directly in a source file:

/*jshint browserify: true */
// browserify code here

Or add it to a .jshintrc file:

{
   "browserify": true
}
like image 101
Alan Plum Avatar answered Oct 08 '22 13:10

Alan Plum


I hate answering my own questions, it feels like theft, but nevertheless, here's the answer. There's a couple of ways to skin this particular cat, but this solution is probably the most "correct"...


Modify .jshintrc

The first thing you should do is modify your .jshintrc so

"globals": {
    "define": false
}

becomes

"globals": {
    "define": false,
    "module": false
}

Modify the code

Now you need to modify the code like this

module.exports = (function(){

    'use strict';

    var myComponent = {};

    myComponent.testController = function($scope){

        $scope.message = 'hello';
        console.log( 'Hello' );

    };

    myComponent.testDirective= function($scope){

        $scope.message = 'hello';
        console.log( 'Hello' );

    };

    return myComponent;

}());

Now JSHint will show linting errors for console.log but not for modules. This is courtesy of the .jshintrc ammend.

The use strict linting error is fixed my wrapping all the code in a function.


require()

Taking this a step further, since we're using browserify, we'll also need require(). So I need to modify .jshintrc one more time.

"globals": {
    "module": false,
    "require": false
}

Note: I've removed define from globals because I'm not using it.

like image 27
gargantuan Avatar answered Oct 08 '22 12:10

gargantuan