The following JS:
(function() {
"use strict";
$("#target").click(function(){
console.log("clicked");
});
}());
Yields:
test.js: line 5, col 3, '$' is not defined.
When linted using JSHint 0.5.5. Any ideas?
This question is related to
javascript
jquery
lint
jshint
If you're using an IntelliJ editor, under
You can type in anything, for instance console:false
, and it will add that to the list (.jshintrc) as well - as a global.
To fix this error when using the online JSHint implementation:
All you need to do is set "jquery": true
in your .jshintrc
.
Per the JSHint options reference:
jquery
This option defines globals exposed by the jQuery JavaScript library.
If you're using an IntelliJ editor such as WebStorm, PyCharm, RubyMine, or IntelliJ IDEA:
In the Environments section of File/Settings/JavaScript/Code Quality Tools/JSHint, click on the jQuery checkbox.
You can also add two lines to your .jshintrc
"globals": {
"$": false,
"jQuery": false
}
This tells jshint that there are two global variables.
You probably want to do the following,
const $ = window.$
to avoid it throwing linting error.
Here is a happy little list to put in your .jshintrc
I will add to this list at time passes.
{
// other settings...
// ENVIRONMENTS
// "browser": true, // Is in most configs by default
"node": true,
// others (e.g. yui, mootools, rhino, worker, etc.)
"globals": {
"$":false,
"jquery":false,
"angular":false
// other explicit global names to exclude
},
}
Instead of recommending the usual "turn off the JSHint globals", I recommend using the module pattern to fix this problem. It keeps your code "contained" and gives a performance boost (based on Paul Irish's "10 things I learned about Jquery").
I tend to write my module patterns like this:
(function (window) {
// Handle dependencies
var angular = window.angular,
$ = window.$,
document = window.document;
// Your application's code
}(window))
You can get these other performance benefits (explained more here):
window
object declaration gets minified as well. e.g. window.alert()
become m.alert()
.window
object.window
property or method, preventing expensive traversal of the scope chain e.g. window.alert()
(faster) versus alert()
(slower) performance.Source: Stackoverflow.com