Lev
Lev

Reputation: 15734

Can VS Code automatically update JavaScript and TypeScript import paths on file rename/move?

Is there a module for vscode that would update paths towards files? e.g. if I have:

import './someDir/somelib'

and I rename or move somelib, would it automatically update the file path in all the files where it is being referred as above?

Upvotes: 58

Views: 89917

Answers (4)

owencm
owencm

Reputation: 8884

Import updating stopped working for me after I set up typescript in my project.

The solution was to follow: https://github.com/microsoft/vscode/issues/66937#issuecomment-475087628

Specifically, to add a jsconfig.json file in the root of my project containing:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2016",
    "jsx": "preserve"
  },
  "exclude": ["node_modules", "**/node_modules/*"]
}

Upvotes: 6

Dhamith Kumara
Dhamith Kumara

Reputation: 864

First go settings

enter image description here

Search 'update import'

enter image description here

You can select:

  • prompt (prompt on each rename)
  • always (Always update path automatically)
  • never (Never rename paths and don't prompt)

Upvotes: 24

Gus
Gus

Reputation: 7545

As @jamey graham mentioned, it stopped working for me in a React typescript project. The fix was to update the tsconfig.json file to have:

{
  "compilerOptions": {
    "baseUrl": "./src",
    // ...
  },
}

and to remove the "include": ["src"] option just for moving the files. VS Code should update the paths nicely after this.

You can bring back the "include": ["src"] option after this.

I do not know why removing the "include": ["src"] worked though.

If this doesn't do the trick, try opening a .ts file and trigger the Typescript: Restart TS server option in the command prompt and try again.

Upvotes: 16

Matt Bierner
Matt Bierner

Reputation: 65503

This feature was added for JavaScript and TypeScript in VS Code 1.24 (tracking issue)

When you move or rename a file, you will now be prompted to see if you want to update imports:

enter image description here

This is controlled by the javascript.updateImportsOnFileMove.enabled and typescript.updateImportsOnFileMove.enabled settings. Valid values are:

  • "prompt" — The default. Prompt for each file rename/move
  • "always" — Always try to update imports automatically without prompting
  • "never" — Do not update imports and do not prompt

Upvotes: 55

Related Questions