Search code examples
javascriptnode.jsvisual-studio-coderequire

Using require with root path variable in VSCode


I am using global variable __root with path of my root app directory then I am using require to load code from other files.

const Parser = require(__root + '/parsers/Parser')

The issue is that vscode does not understand what is happening:

  1. Intellisense does not work
  2. Object type is shown as any (if path is correct vscode grabs right type)

What are the options to solve this? Can you share your practices to resolve this issue?


Solution

  • VS Code's intellisense cannot understand dynamic import paths like root + '/path'. There are no workarounds for this, nor are the plans to address this in the immediate future.

    However, with static require import paths, you can configure how VS Code resolves the imports by configuring a jsconfig.json. The two options you probably want are baseUrl and paths

    Setting up a jsconfig.json will not change the runtime behavior of your code, only how VS Code IntelliSense handles your project. You can use a jsconfig.json along with webpack aliases