eslint /* exported functionName */ not working in browser env - javascript

I have a few functions that are defined in one js file and used in others. They each have /* exported functionName */ comments and I have my eslint env set to browser/jquery. Based on my reading of the documentation that's all I should need, but it doesn't seem to be working.
What am I doing wrong here?
Here's the .eslintrc (it extends this one, although I get the same behavior without the extends):
{
"extends": "../../.eslintrc",
"env": {
"browser": true,
"jquery": true
}
}
And, here's one of the functions (here's the second and third):
/**
* Returns the next hour as Date
* #return {Date} the next hour
*/
/* exported nextHour */
function nextHour() {
var oneHour = new Date();
oneHour.setHours(oneHour.getHours() + 1);
return oneHour;
}
Finally, this is the output I get from eslint:
/Users/nfriedly/visual-recognition-nodejs/public/js/demo.js
24:10 error 'nextHour' is defined but never used no-unused-vars
37:10 error 'resize' is defined but never used no-unused-vars
/Users/nfriedly/visual-recognition-nodejs/public/js/use.js
26:10 error 'setupUse' is defined but never used no-unused-vars
It works if I replace the /* exported... comment with an // eslint-disable-next-line no-unused-vars but I know that's not the correct solution.
You can check out the complete project from https://github.com/watson-developer-cloud/visual-recognition-nodejs/tree/eslint-exported and then just run npm install; npm test if you want to see it for yourself.

Apparently the Babel-ESLint parser that the airbnb config specifies can override the parsing of config files to break the documented cascading behavior. Setting "parser": null resolves this.

Your config states that you are working in Node environment. Node has an extra scope around every module, so global variables are not really possible in Node (at least not in the same way as in browser). As such, when no-unused-vars rule sees any environment with globalReturn flag on (Node, CommonJS, shared-node-browser) or modules on, it ignores /* exported */ comments. You need to remove Node environment and enable browser environment if you want to use global variables and exported comments.

Related

React assigned value but never used in an unexisting file

Im using create-react-app to make my aplication. After I save the files to compile the terminal throws the folowing error:
src\App.js
Line 37:21: 'setOpenModal' is assigned a value but never used no-unused-vars
src\App\App.js
Line 37:21: 'setOpenModal' is assigned a value but never used no-unused-vars
the thing is, the file App.js I moved to a file called App and changed the name to index.js. Also I sent the variable setOpenModal to a element like so:
src/App/index.js:
const [openModal, setOpenModal] = React.useState(false);
return (
<AppIU
doc_type={doc_type}
date={date}
course={course}
openModal={openModal}
setOpenModal={setOpenModal}
/>
);
the function setOpenModal is actually being used in another file and I pass the fuction through props. is there a way to make react realice that the variable is being used and that the file src/App.js no longer exists??
I've tried just saving again the file to compile it again expecting the warnig to just go away but it persists. Ive also tryed adding the /* eslint-disable no-unused-vars / and / eslint-enable no-unused-vars */ before and after declerign the const but it still does not remove the warning. Also I would like to not jus disable the warnings as I have a tendency to forget about decleared variables :v
I'd shutdown the server, delete the cache and build files, and then start the development server again.
There was the answer for your issue:
First, install the following module npm install --save-dev eslint-plugin-react.
Then, in your .eslintrc.json, under extends, include the following plugin:
'extends': [
'plugin:react/recommended'
]
ESLint with React gives `no-unused-vars` errors

TypeScript checks and declarations in regular JS

So basically I would like to use TypeScript to check my code for errors while in editor (VS Code), but don't want to do any transpilation steps.
I have my code in .js files, and "allowJs": true in tsconfig.json
The only problem is, the editor would complain about usage of typescript-words inside js files, for example:
declare module "something" {
export interface MyInterface {
Leads to error:
"'module' declarations can only be used in TypeScript files"
I tried not to give a damn but unfortunately, it also leads to error while running the actual (node.js) program!
SyntaxError: Unexpected strict mode reserved word
at Loader.moduleStrategy (internal/modules/esm/translators.js:145:18)
Can't I somehow have TS checks without TS?
I know I can, I mean it's right there but then I have to delete everything related to TS before app launching.
IDK maybe someone has a... transpiler for that? :D
Surprisingly there's not much information about this on the Internet.
The reasons why I won't transpile TS to JS:
It spends time
The code is a mess. It has random functions I never wrote, also "var"
everywhere
Errors have line numbers from .JS files which are autogenerated (f**ked up)
Why would I compile a scripting language anyway
Yeah, you absolutely can. And you don't need TypeScript declaration files either.
TypeScript will happily check your vanilla JS code if you have the checkJs flag set in either CLI config or your tsconfig.json file. allowJs actually has nothing to do with it, that just enforces whether you can import vanilla JS files into TS/TSX files (it doesn't care if you import JS into JS). JSDoc annotation is actually a great way to mix vanilla JS and TS code in a mixed codebase, for example if you're in the process of migrating code from JS to TS.
TypeScript (even without JSDoc annotations) will give you tons of useful "implicit" type checking without writing any extra syntax, just by detecting how you declare variables and assuming that their type shouldn't change (among other inferences):
// Implicit TypeScript typing
let myBooleanValue = false;
myBooleanValue = 'true'; // Error: Type 'string' is not assignable to type 'boolean'.ts(2322)
If you want even more control however, TypeScript is fully compatible with JSDoc type annotations. Make sure you read the documentation and use the proper comment syntax (e.g. /** ... */ not // ...). There's just about nothing you can do with TypeScript syntax that you can't do with JSDoc, it's just a bit wordier:
// Explicit JSDoc typing
/**
* #type {string}
*/
let myVar;
myVar = 7; // Error: Type 'number' is not assignable to type 'string'.ts(2322)
You can get even more advanced with it, declaring things like function parameters, object structure and nested fields, return values, and more:
/**
* #param {object} myParam
* #param {number} myParam.myNumber
* #returns {boolean} // Error: A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355) (because nothing is currently returned from myFunction)
*/
function myFunction(myParam) {
let myNumberCopy = myParam.myNumber;
let myMissingPropertyCopy = myParam.myMissingProperty; // Error: Property 'myMissingProperty' does not exist on type '{ myNumber: number; }'.ts(2339)
}
You can even do crazy stuff like import types from other files or packages and use it in your JSDoc annotations:
/**
* #type {import("React").FC}
*/
const MyComponent = () => null;
Here is the tsconfig.json file I used for the above examples, with nothing except basic typescript NPM package installed:
{
"compilerOptions": {
"module": "es6",
"noEmit": true,
"checkJs": true,
"moduleResolution": "node"
},
"include": ["src/**/*"]
}
Visual proof that this all works great in VSCode:
With this setup a good way to "test" whether you have any type errors in your entire codebase is to run npx tsc --noEmit, which will run TypeScript checking (including the JSDoc annotations) for all your files, according to your tsconfig.json file.

JSDoc Typescript Checking of Named Default Params

Given the following
/**
* #param {{bar?: string|null}} [param0]
*/
const foo = ({bar = null} = {}) => bar;
Typescript 3.7.2 reports
var bar: string | null
Binding element 'bar' implicitly has an 'any' type.ts(7031)
The JavaScript code works how I want it to, but how can I write the jsdoc hint so that TypeScript understands that the destructured bar variable is string|null not any?
Update with correct answer
The problem found is actually your tsconfig and how the JavaScript type checking works with it. The option that is causing the difference between your config and mine is the strict property. According to the config documentation:
Enabling --strict enables --noImplicitAny, --noImplicitThis, --alwaysStrict, --strictBindCallApply, --strictNullChecks, --strictFunctionTypes and --strictPropertyInitialization.
Adding each of those options to my tsconfig, I discovered that disabling two of those options would get rid of the reported error. Those options are:
--strictNullChecks
--strictPropertyInitialization (because it can't be enabled without the --strictNullChecks option)
When I disabled those two, it was finally happy with the result.
I copied the example into a TypeScript file to see if it had a similar problem.
The TypeScript version reported no errors with the same exact type signature, but the JavaScript version was ignoring the JSDoc altogether. However, looking at the rest of the code, it still was registering the bar variable as being of type string|null.
Coming to this conclusion, it is likely a bug in the JavaScript type checking and how it works with those options despite neither of those options seemingly being related to this case.
EDIT:
I've checked and it looks like there is a bug already logged for this on the TypeScript repo:
https://github.com/microsoft/TypeScript/issues/31372
Previous solution (which didn't work)
You should be able to do this easily. Maybe remove the square brackets from the param name in the jsdoc comment. This example works fine:
/**
* #param {{bar?: number|null}} _
*/
const foo = ({ bar = null } = {}) => {
// do stuff with bar
}
The tsconfig that I have looks like this:
{
"compilerOptions": {
"checkJs": true,
"allowJs": true,
"outDir": "node_modules/.tmp/",
"noImplicitAny": true
},
"include": [
"index.js"
]
}
Here is the repo that has this code you can use to check on your side, too:
https://github.com/cwadrupldijjit/js-typescript-checking
The version of TypeScript that this was tested in is 3.7.2
EDIT:
Checked out the square brackets vs non-square brackets and it looks like it doesn't matter. TSC is fine with it either way.

xo lint error: `document` is not defined

I've been a long time user of Standard, and now that I'm working on a new project, I've been asked to start writing semicolons.
I'm trying to use both xo, Babel and React, but I keep getting an error when I try to lint my code:
document is not defined. no-undef
I've tried adding an env option to the xo field in my package.json file, but no success.
My xo config:
"xo": {
"esnext": true,
"extends": "xo-react",
"space": true,
"rules": {
"react/jsx-space-before-closing": 0
}
}
It is cumbersome to specify linting options such as /** global document **/ and edit a configuration file every time you use a global.
This error can be suppressed by using --env=browser option:
xo --env=browser [<file|glob> ...]
Note: Same problem comes with Node.js, where the linter will complain that require and friends are not defined. The switch has to change to --env=node in that case.
However, XO defaults the env to node, therefore this will not be a problem in most cases. You will need multiple environments if your project contains both client and server files. in that case, --env switch can be set multiple times:
xo --env=browser --env=node [<file|glob> ...]
You have to define globals in ESLint. There are two ways to accomplish this, firstly as a comment in your code:
/* global document */
Or you can configure in configuration file like so:
{
"globals": {
"var1": true,
"var2": false
}
}
See the ESLint docs for more

How to tell JSLint / JSHint what global variables are already defined

In my project we have some global variables that work as containers:
MyProject.MyFreature.someFunction = function() { ... }
So then I use that script across the site and JSLint / JSHint complains about that:
'MyProject' is not defined
I know that I can go to every JavaScript file and add the comment /*global MyProject*/ on top of it. But I'm looking a way to define that comment in some sort of config file so I don't have to go file by file adding this comment.
Some kind on option in the config/jshint.yml would be nice.
For JSHint you can create .jshintrc to your project directory with
{
"globals": { "MyProject": true }
}
This is only for globals
/* global MyProject */
In your case you need
/* exported MyProject */
JSLint has a textarea below the options that says predefine global variables here in it. Just add the variable names in there before running the check.
JSHint doesn't allow you to add global variables, but you can uncheck the When variable is undefined option to suppress that warning.
The JSHint library also has parameters for globals, if you run it as a library . . . details in here: http://jshint.com/docs/

Categories

Resources