I have just started using JSHint (through the Sublime-Linter package for Sublime Text 2). I would like to suppress its warnings regarding functions that are used before they are defined, as I see no problem with using function definitions like this. For example, the following code generates warnings:
(function($){
$(document).ready(function()
{
formValidationSetup();
refreshErrorMessages();
});
function formValidationSetup()
{
}
function refreshErrorMessages()
{
}
})(jQuery);
The warnings:
formValidationSetup is defined but never used
refreshErrorMessages is defined but never used
I've tried setting undef to false in the JSHint options, but I'm still getting these errors. Is there another option I should be setting? Form the JSLint docs for undef:
true if variables and functions need not be declared before used. This
is not available in strict mode.
To avoid the warning
defined but never used
in jslint in your javascript add comments like:
/*exported formValidationSetup, refreshErrorMessages */
In jshint and jslint you can set the unused option to false:
/*jshint unused:false*/
See Options
I had this problem with should and expect in Chai tests. I ended up with this pattern:
'use strict';
var request = require('supertest');
var should = require('chai').should(); // jshint ignore:line
var expect = require('chai').expect; // jshint ignore:line
process.env.NODE_ENV = 'test';
var appPromise = require('./index');
describe('GET /r_u_up', function() {
it('respond with 204', function(done) {
appPromise.then(function(app) {
request(app)
.get('/r_u_up')
.expect(204, done);
});
});
});
You can simply use
"unused": false,
in your .jshintrc
Interestingly, adding 'use strict'; inside the IIFE suppresses the error. Not sure why though.
A better way not touching the Gruntfile.js in a typical Yoeman setup is to edit the .jshintrc file (a hidden file in Unix system). And update the content as the following:
{
"curly": true,
"eqeqeq": true,
"immed": true,
"latedef": true,
"newcap": true,
"noarg": true,
"sub": true,
"undef": true,
"unused": false, // the change is here
"boss": true,
"eqnull": true,
"node": true
}
set the "unused" to false.
You'll want to use the 'latedef' option
Related
I am importing a script in webpack, it all works but eslint is throwing the error 'modal is assigned a value but never used'. Do have to declare the const as a global or export the module to fix the error ?
modules.vanillaModal.js :
import VanillaModal from 'vanilla-modal';
// Create instance
const modal = new VanillaModal({
modal: '.c-modal',
modalInner: '.js-modal__inner',
modalContent: '.js-modal__content',
open: '[rel="js-modal:open"]',
close: '[rel="js-modal:close"]',
class: 'js-modal--visible',
loadClass: 'js-modal--loaded',
});
and my webpack entry
index.js:
require('./modules.vanillaModal.js');
This is an eslint rule http://eslint.org/docs/rules/no-unused-vars. It prevents you from creating variables that you never use, which causes code clutter or could mean you're using variables that aren't what you think they are.
If you're using a poorly designed library where the class constructor has side effects (which it isn't supposed to), and you don't need to do anything with the returned value from the class, I would disable that specific eslint rule for the create line with eslint disable comments:
// eslint-disable-next-line no-unused-vars
const modal = new VanillaModal({
modal: '.c-modal',
modalInner: '.js-modal__inner',
modalContent: '.js-modal__content',
open: '[rel="js-modal:open"]',
close: '[rel="js-modal:close"]',
class: 'js-modal--visible',
loadClass: 'js-modal--loaded',
});
You can also wrap any block of code with eslint specific comments to disable a rule for that block:
/* eslint-disable no-unused-vars */
const modal = new VanillaModal({
...
});
/* eslint-enable no-unused-vars */
According to the documentation of the no-unused-vars rule, you should be able to just add an EsLint configuration comment to declare the variable as exported to be used elsewhere.
/*exported modal*/
const modal = new VanillaModal({
modal: '.c-modal',
modalInner: '.js-modal__inner',
modalContent: '.js-modal__content',
open: '[rel="js-modal:open"]',
close: '[rel="js-modal:close"]',
class: 'js-modal--visible',
loadClass: 'js-modal--loaded',
});
It will work with constants too.
I find this better than disabling and re-enabling the rule again because I just need one comment instead of two.
Add "varsIgnorePattern:" to .eslintrc file
"no-unused-vars": ["warn", { "varsIgnorePattern": "VARIABLE_NAME"}]
https://eslint.org/docs/rules/no-unused-vars#varsignorepattern
Do you have .eslintrc.js file ?
simply add :
"rules": {
"no-unused-vars": 0
}
I have a Node.js web application where I use Backbone.js and jQuery. My main js file is app.js where I include all the necessary scripts, including jQuery. So, this is the beginning of my app.js code:
'use strict';
var _ = require('lodash');
var $ = require('jquery');
var B = require('backbone');
B.$ = $;
Now if I run grunt on my project, it raises errors at the line where jQuery is loaded to $. It shows me this:
Linting public/js/app.js ...ERROR
[L4:C5] W079: Redefinition of '$'.
var $ = require('jquery');
I can still get everything running with grunt --force, but I would like to eliminate this error anyway. Can somebody explain why it raises the error and how to fix it?
My .jshintrc file:
{
"laxcomma": true
,"laxbreak": true
,"curly": true
,"eqeqeq": true
,"immed": true
,"latedef": true
,"newcap": true
,"noarg": true
,"sub": true
,"undef": true
,"unused": false
,"asi": true
,"boss": true
,"eqnull": true
,"node": true
,"browser": true
,"jquery": true
,"predef":
[
"suite"
,"test"
,"setup"
,"teardown"
,"suiteSetup"
,"suiteTeardown"
,"requestAnimationFrame"
]
}
In jshint docs: http://www.jshint.com/docs/options/
jquery = true
This option defines globals exposed by the jQuery JavaScript library.
You are telling jshint that jquery exists, thus he assumes that $ is defined. Remove the "jquery" : true" and your issue should go away.
Add this at the top of the file to make that error go away:
/* jshint -W079 */
What's happening here is that JQuery defines the $ variable, so JSHint views this as a piece of "potentially dangerous code"
A better solution would be to require jquery directly which should give you access to the $ variable globally.
Random guess: do you include jquery somewhere else? For example in some html file as a script. Or some other script might be defining global jquery variable.
Make sure that in your .jshintrc you don't have '$' set as predefined.
// Predefined Globals
"predef" : ["$"]
If it is, remove.
I uses RequireJS AMD in my project. When i run jshint on my project, it throws error like
In AMD Scripts
'define' is not defined.
In Mocha test cases
'describe' is not defined.
'it' is not defined.
How to remove this warning in jshint?
Just to expand a bit, here's a .jshintrc setup for Mocha:
{
....
"globals" : {
/* MOCHA */
"describe" : false,
"it" : false,
"before" : false,
"beforeEach" : false,
"after" : false,
"afterEach" : false
}
}
From the JSHint Docs - the false (the default) means the variable is read-only.
If you are defining globals only for a specific file, you can do this:
/*global describe, it, before, beforeEach, after, afterEach */
jshint: {
options: {
mocha: true,
}
}
is what you want
To avoid the not defined warning in jshint for the javascript add comments like:
/*global describe:true*/
Options
Add this in your .jshintrc
"predef" : ["define"] // Custom globals for requirejs
late to the party, but use this option in your jshintrc:
"dojo": true
and thou shall rest peacefully without red warnings...
If you are working on node js. Add these two lines in the beginning of your file
/*jslint node: true */
"use strict";
Read the docs and search for /*global
If you're trying to run JSHint in WebStorm with Mocha, as I am, go into:
WebStorm > Preferences > Languages & Frameworks > JavaScript > Code Quality Tools > JSHint
Scroll down to "Environments" and make sure you have selected the checkbox to enable "Mocha" which will set up the definitions for JSHint for Mocha for you.
I'm trying to get started with Buster.js, and I installed both buster and buster-amd, but even so my use of Require.js is causing problems. My buster.js file looks like this:
var config = module.exports;
config["My tests"] = {
autoRun: false,
environment: "browser", // as opposed to "node"
extensions: [require("buster-amd")],
rootPath: "../",
sources: ['ext/require/require.js'],
tests: ["buster-test/*-test.js"]
};
and my test like this:
define(['buster-test/buster'
], function(buster) {
buster.spec.expose(); // Make some functions global
describe("A Fake Test", function () {
it("can be instantiated", function () {
console.log('test')
});
});
buster.run()
});
But when I try to run the above, I get:
Uncaught exception: ./buster/load-all.js:1 Uncaught ReferenceError: require is not defined
TypeError: uncaughtException listener threw error: Cannot read property 'id' of undefined
at Object.module.exports.uncaughtException (/usr/lib/node_modules/buster/node_modules/buster-test-cli/lib/runners/browser/progress-reporter.js:42:50)
at notifyListener (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/bane/lib/bane.js:49:35)
at Object.object.emit (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/bane/lib/bane.js:127:17)
at Object.module.exports.bane.createEventEmitter.emitCustom (/usr/lib/node_modules/buster/node_modules/buster-test-cli/lib/runners/browser/remote-runner.js:289:14)
at /usr/lib/node_modules/buster/node_modules/buster-test-cli/lib/runners/browser/remote-runner.js:92:16
at PubSubClient.on._handler (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/ramp/lib/pubsub-client.js:73:43)
at Object.Faye.Publisher.trigger (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/ramp/node_modules/faye/node/faye-node.js:385:19)
at Object.Faye.extend.Set.Faye.Class.distributeMessage (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/ramp/node_modules/faye/node/faye-node.js:668:30)
at Object.Faye.Client.Faye.Class._deliverMessage (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/ramp/node_modules/faye/node/faye-node.js:1070:20)
at Object.Faye.Client.Faye.Class.receiveMessage (/usr/lib/node_modules/buster/node_modules/buster-test-cli/node_modules/ramp/node_modules/faye/node/faye-node.js:1007:12)
Has anyone seen anything like this before, and if so do you have any suggestions as to what I'm doing wrong?
P.S. If I remove the extensions: line I get a similar error, except that it complains about define instead of require. So it seems like the failure to find require is happening inside the plug-in ... but I have no idea how to provide Require to the plug-in.
Have you tried adding the require.js to libs instead of sources on your buster config? So the config would look like this:
var config = module.exports;
config["My tests"] = {
autoRun: false,
environment: "browser", // as opposed to "node"
libs: [ 'ext/require/require.js' ],
extensions: [require("buster-amd")],
rootPath: "../",
tests: ["buster-test/*-test.js"]
};
I take a different approach. I don't disable autorun, but instead use Buster's async test case format where you define the test case as a function that's passed a run callback. Use the (not well documented) resources: config setting to allow require to load your source code.
config["Browser tests"] = {
environment: "browser",
libs: [ 'test/require_config.js','require.js' ],
rootPath: "../",
resources: ["your_source_code/**/*.js"],
tests: ["buster-test/*-test.js"]
};
Then use require() in your tests, and when you've loaded your code call the run callback with the tests:
buster.testCase("AppCode",function(run) {
require(["appCode"],function(appCode) {
run({
"it works": function() { assert(true) }
})
});
});
I've created an example project showing this method require.js with buster.js. It has a small helper function to do both the testCase and require call simultaneously.
I'm trying to use lint with Grunt. I'm able to run Grunt from the command line but it is giving me a lot of errors. Mostly "'$' is not defined". Even alert is throwing an error, "'alert' is not defined".
How can I get around those?
You need to tell JSHint (which is the linter that Grunt uses by default) about the global variables available to the files being linted. I'm assuming that you're including jQuery on your pages, hence the $ identifier (could be various other libraries of course).
You can either specify global variables in each file, or in the Grunt script. To specify them in a file, you can use a global directive. Place this at the top of the file, or at the top of the function in which you use the global:
/*global $:false */
Note that the false means you'll get errors if you override $. If you need the ability to do that, change it to true.
If you'd prefer to specify globals in the Grunt script, you can add a globals property to any of the tasks in your jshint section. For example:
grunt.initConfig({
jshint: {
someTask: {
globals: {
$: false
}
}
}
});
As for the alert message you're getting, you need to tell JSHint that you're allowing the use of development functions, such as alert and console.log. To do that, you can use a jshint directive in the files (just like the global directive):
/*jshint devel:true */
Or you can add an options property to the task in the Grunt script:
someTask: {
globals: {
$: false
},
options: {
devel: true
}
}
See the JSHint docs for all of the options available to you.
globals must be inside options
someTask: {
options: {
devel: true,
globals: {
$: false
}
}
}