简体   繁体   中英

Why does VSCode's “Go to definition” fail on my project using Webpack alias?

This is a followup to vscode issue #16320 , to which vscode dev Matt Bierner suggests I ask here.


Recent versions of VS Code...

  1. ... have a Go to definition feature, triggered by pressing F12 on a symbol...
  2. ... and also support (via jsconfig.json configuration) webpack aliases, a webpack feature enabling prefixes for import lines for friendlier imports (see vscode documentation for Webpack aliases ). For example, aliasing /src/api to * will let me type import foo from */users instead of import foo from ../../../../src/api/users .

But in some uses cases, they fail together. I built a minimal broken test project (zip, 3kB) for my use case. Can anyone give a look at it and see if I'm doing anything wrong or if it looks like a bug?

Extract the zip and see README.md : path autocompletion works, but not "peek" or "Go to definition".

  • Skim through the js files to check I'm not asking you to run anything nefarious.
  • npm install && npm run build && node dist/index.js → Install & build both succeed, indicating Webpack is happy. Run logs [1, 2, 3] .
  • Now, run code /path/to/project and open src/index.js On line 5, try to F12 on getLinksNo definition found for 'getLinks' 😢

Am I still doing something wrong in my jsconfig.json , or is this a bug? (the multiple levels of exports, maybe?)

Accepted answer is correct, except my solution was simply:

import something from '~/something';

jsconfig.json looks like this:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"]
    }
  }
}

Change src/index.js like below:

import { Links } from 'api/resources';

Change jsconfig.json file paths like below:

"paths": { 
    "api/*": ["./src/api/*"] 
}

in src/api/resourcers/index.js change your import export like below:

import * as Links from './links';

export {Links};

also install this package and use --save-dev option

npm install --save-dev babel-plugin-module-resolver

after this add the plugin to babel plugins in package.json I don't know if you need the root prefix plugin but I removed it.

"plugins": [
  "transform-runtime",
  "transform-export-extensions",
  "transform-object-rest-spread",
  [
    "module-resolver", {
    "root": ["./src"],
    "alias": {
      "api": "./src/api"
    }
  }
]

you can also change api to resources but in that case you need to import like below:

import {Links} from 'resources/index';

Also please check this and this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM