Fattie
Fattie

Reputation: 12590

In Node.js how to notice a missing function?

In some Node.js, I had

function examp() {
    ..
    blah = bestAvailableDelauneySlot()
    ..
}

However the function bestAvailableDelauneySlot did not exist at all.

(In my case I had foolishly forgotten to type the module, so, it should have been blah = triangles.bestAvailableDelauneySlot() ..)

Now, the code

  blah = bestAvailableDelauneySlot()

doesn't create any error AT ALL, until, for some reason examp is called at runtime. (Which only happens in obscure situations, once a week).

VSCode does not at all tell me there is no definition for bestAvailableDelauneySlot. "using strict" does not seem to help.

How the heck to safeguard against an undefined function name??

A simple typo

blah = triangles.bestAvailableDelauneySlozz()

and crash. Solution?

Perhaps ideally something that integrates w/ VSCode?

(BTW I generally use VSCode on a Mac ... perhaps that's the problem :O )

Upvotes: 5

Views: 1108

Answers (2)

Jack Yu
Jack Yu

Reputation: 2425

I want to provide two methods. I hope it could help you. More detail in Type checking JavaScrip.
Note: this is vscode.

First

You could simply add // @ts-check in the head of file to validate. Before you add // @ts-check, it doesn't tell you an error (bestAvailableDelauneySlot doesn't exist).

enter image description here

Then you add // @ts-check, it will tell you it doesn't exist.

enter image description here

Then you declare the function, the error is gone.

enter image description here

If you make some typo, it will show error message.

enter image description here

And it also work in module.exports and require. No // @ts-check.

enter image description here

Add // @ts-check.

enter image description here

Second

If you don't want to add //@ts-check by every file, you could create jsconfig.json in project root to enable whole files checking with adding checkJs in jsconfig.json. Its effect is same as adding //@ts-check in all files.

{
    "compilerOptions": {
        "checkJs": true
    },
    "exclude": ["node_modules", "**/node_modules/*"]
}

Upvotes: 3

xehpuk
xehpuk

Reputation: 8241

The tool ESLint is the de facto standard to check for problems in JavaScript code.

In your specific case, the rule no-undef would report the undeclared function.

There's also an extension for Visual Studio Code with more than 12 million downloads:

ESLint for Visual Studio Code applied to the example

Upvotes: 5

Related Questions