pom421
pom421

Reputation: 1964

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 :

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)

Upvotes: 3

Views: 4199

Answers (1)

pom421
pom421

Reputation: 1964

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)
}

Upvotes: 3

Related Questions