How to Autocomplete ES Modules With Webpack in VSCode

Visual Studio Code is my preferred editor these days (supplemented with Vim, of course). VSCode is an IDE with decent Javascript autocompletion and intellisense. However, it's unable to resolve Webpack custom module paths out of the box.

Before

After

Hovering over a symbol while holding down ⌘ now shows the correct definition! Hooray!

Webpack Modules Directories?

Webpack has a convenient feature to specify base paths to look in when importing ES modules. For example, you might have this Webpack configuration:

{
  resolve: {
    modulesDirectories: [
      'src'
    ]
  }
}

If you have a file that lives in src/components/Page.js, you can now import it with import Page from 'components/Page.js' and not worry about where components/ lives, or where the requirer and requiree are relative to each other.

This confuses VSCode's jump to definition feature. Let's fix that!

The Fix: VSCode's "paths" Array

Open or create the file jsconfig.json in your project's root. If you're in a TypeScript project, use tsconfig.json instead.

Given this Webpack config as an example:

  resolve: {
    modulesDirectories: [
      'src',
      'assets'
    ],

Add the following to your jsconfig.json:

{
  "compilerOptions": {
    // This must be specified if "paths" is set
    "baseUrl": ".",
    // Relative to "baseUrl"
    "paths": {
      "*": [
        "*",
        "src/*",
        "assets/*"
      ]
    }
  }
}

Rules for the above:

  • Put it in a top level compilerOptions key
  • Leave baseUrl as . (current directory)
  • Always include "*" as the first entry in the paths array (I have no idea why).
  • Directories must end with "/*" (I have no idea why).
  • Yes, it's a mapping from "*" to an array that contains "*". I have no idea why.

You can read more about path mapping in the VSCode TypeScript handbook. I agree this is not an intuitive place for this documentation!

Alternate Solutions

I haven't tested this, but according to this GitHub comment you can install the "Path Intellisense extension" and add the following to a "path-intellisense.mappings" key in your settings.json file:

{
  "path-intellisense.mappings": {
    "/": "${workspaceRoot}",
    "src": "${workspaceRoot}/src",
    "assets": "${workspaceRoot}/assets"
  },
}

That's It!

If this helped improve your VSCode setup, consider following me on Twitter.

comments powered by Disqus