Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate in Javascript code in Visual Studio Code?

I wonder how to navigate in Javascript code in VS code.

To figure out the behavior, I made this little project :

  • js
  • js/index.js
  • js/foo.js

index.js

var person = {}

person.name = "azeaze"

person.sayHello = function() {
  console.log("Hi! My name is ", this.name)
}

foo.js

console.log('In foo module')

person.sayHello()

jsconfig.json

{
    "compilerOptions": {
        "target": "ES5"
    },
    "exclude": [
        "node_modules"
    ],
    "include": [
        "js/*"
    ]
}

What I need is to navigate, from the foo.js file when I click on person.sayHello. I tried Cmd-click or F12 but VS Code replies "No definition found for sayHello". Why VS code can't?

May be the use of module is required? If so, is there a way to handle legacy code (pure ES5 code) who don't provide it? And what the purpose of "include" in jsconfig.json, if the IDE only need to follow the require?

Edit : I tried to follow this answer Debugging/Navigating JS Code in Visual Studio, that is to say add to foo.js :

/// <reference path="../Path/To/The/Referenced/index.js" />

But F12 navigation still doesn't work.

(I'm on Mac OS 10.12 and VS Code 1.13)

like image 498
pom421 Avatar asked Jun 07 '26 17:06

pom421


1 Answers

I copy/paste the answer from the official github's VS Code : https://github.com/Microsoft/vscode/issues/28495#event-1119847030.


The TypeScript service that powers our JS and TS language currently cannot recognize properties added to an object after it is created.

The best workaround is to define all the properties in the object literal:

var person = {
   name: "azeaze",
   sayHello: function() {
     console.log("Hi! My name is ", this.name)
  }
}

or to add an explicit type using jsdocs:

/**
 * @type {{ name: string, sayHello: () => void}}
 */
// @ts-ignore
var person = {}

person.name = "azeaze"

person.sayHello = function() {
  console.log("Hi! My name is ", this.name)
}
like image 184
pom421 Avatar answered Jun 09 '26 08:06

pom421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!