Question

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?

Was it helpful?

Solution

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
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top