简体   繁体   中英

Visual Studio Code Automatic Imports

I'm in the process of making the move from Webstorm to Visual Studio Code. The Performance in Webstorm is abysmal.

Visual studio code isn't being very helpful about finding the dependencies I need and importing them. I've been doing it manually so far, but to be honest I'd rather wait 15 seconds for webstorm to find and add my import that have to dig around manually for it.

截图:找不到导入

I'm using the angular2 seed from @minko-gechev https://github.com/mgechev/angular2-seed

I have a tsconfig.json in my baseDir that looks like this:

    {
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": false,
    "removeComments": true,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "pretty": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitUseStrict": false,
    "noFallthroughCasesInSwitch": true
  },
  "exclude": [
    "node_modules",
    "dist",
    "typings/index.d.ts",
    "typings/modules",
    "src"
  ],
  "compileOnSave": false
}

and I have another one in my src/client dir that looks like this:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "allowSyntheticDefaultImports": true
  }
}

I don't know why there are two. The angualr seed project uses typescript gulp build tasks so I guess the compilation is different.

What can I do get vscode to be more helpful??

2018 now. You don't need any extensions for auto-imports in Javascript (as long as you have checkjs: true in your jsconfig.json file) and TypeScript.

There are two types of auto imports: the add missing import quick fix which shows up as a lightbulb on errors:

在此处输入图片说明

And the auto import suggestions . These show up a suggestion items as you type. Accepting an auto import suggestion automatically adds the import at the top of the file

在此处输入图片说明

Both should work out of the box with JavaScript and TypeScript. If auto imports still do not work for you, please open an issue

I got this working by installing the various plugins below.

Most of the time things just import by themselves as soon as I type the class name. Alternatively, a lightbulb appears that you can click on. Or you can push F1 , and type "import..." and there are various options there too. I kinda use all of them. Also F1 Implement for implementing an interface is helpful, but doesn't always work.

List of Plugins

Screenshot of Extensions

扩展程序截图
* click for full resolution

I used Auto Import plugin by steoates which is quite easy.

Automatically finds, parses and provides code actions and code completion for all available imports. Works with Typescript and TSX.

In the tsconfig.app.json, a standard Angular 10 app has:

{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

Once I changed the include like to be:

  "include": [
    "src/**/*.d.ts",
    "src/**/*.ts"
  ]

It worked for me它对我有用

If anyone has run into this issue recently, I found I had to add a setting to use my workspace's version of typescript for the auto-imports to work. To do this, add this line to your workspace settings:

{
  "typescript.tsdk": "./node_modules/typescript/lib"
}

Then, with a typescript file open in vscode, click the typescript version number in the lower right-hand corner. When the options at the top appear, choose "use workspace version", then reload vscode .

Now auto-imports should work.

VS Code supports this out of the box now, but the feature sometimes works and sometimes doesn't, it seems. As far as I could find out, VS Code has to load data needed for auto imports, which happens more or less like this:

  • Load data for all exports from your local files
  • Load data for all exports from node_modules/@types
  • Load data for all exports from node_modules/{packageName} only if any of your local files is importing them

This is better described in this comment: https://github.com/microsoft/TypeScript/issues/31763#issuecomment-537226190 .

Due to bugs either in VS Code or in specific packages' type declarations, the last two points don't always work. That was my case, I couldn't see react-bootstrap auto imports in a plain Create-React-App. What finally fixed it was manually copying the package folder from node_modules to node_modules/@types and leaving there only the type declaration files, eg Button.d.ts. This is not great because if you ever delete node_modules folder it will stop working again. But I prefer this from always having to manually type imports. This was my last resort after trying and failing with these methods:

  • Update VS Code (v. 1.45.1)
  • Install types for your package, eg npm install --save @types/react-bootstrap
  • Add jsconfig.json file and play with the settings as other people suggested
  • Try out all the plugins for automatic imports

I hope this helps someone!

For Javascript projects:

  • Set Check JS settings flag works for me.
  • No need to create a jsconfig.json in project

在此处输入图片说明

在此处输入图片说明

If you are using angular, check that the tsconfig.json does not contain errors. (in the problems terminal)

For some reason I doubled these lines, and it didn't work for me

{
  "module": "esnext",
  "moduleResolution": "node",
}

Fill the include property in the first level of the JSON-object in the tsconfig.editor.json like here:

"include": [
  "src/**/*.ts"
]

It works for me well.

Also you can add another Typescript file extensions if it's needed, like here:

"include": [
  "src/**/*.ts",
  "src/**/*.spec.ts",
  "src/**/*.d.ts"
]

Take a look at this first MUST HAVE EXTENSIONS and install the extensions that you may need. And then, the following works for me just fine.

{
    "compilerOptions": {
        "target": "es5",
        "allowSyntheticDefaultImports": true
    }
}

I've come across this problem on Typescript Version 3.8.3.

Intellisense is the best thing we could have but for me, the auto-import feature doesn't seem to work either. I've tried installing an extension even though auto-import didn't work. I've rechecked all the settings related to extensions. Finally, the auto-import feature started working when I clear the cache, from

C:\\Users\\username\\AppData\\Roaming\\Code\\Cache

& reload the VSCode

Note: AppData can only be visible in username if you select, Show (Hidden Items) from (View) Menu.

In some cases, we may end up thinking there is an import related error, while in actuality, unknowingly we might be coding using deprecated features or APIs in angular.

For example: if you're trying to code something like this

constructor (http: Http) {

//...}

Where Http is already deprecated and replaced with HttpClient in the newer version, so we may end up thinking an error related to this might be related to the auto-import error. For more information, you can refer Deprecated APIs and Features

Typescript Importer does do the job for me

https://marketplace.visualstudio.com/items?itemName=pmneo.tsimporter

It automatically searches for typescript definitions inside your workspace and when you press enter it'll import it.

Add "typeRoots" attribute in tsconfig.json:

"typeRoots": [
      "node_modules/@types",
      "node_modules/@angular",
      "node_modules/@angular/common/http"
    ]

You may add any other necessary path.

In JavaScripts projects like ReactJs or React-Native just follow theses steps.

1 = First remove all the auto import plugins becuase vc code automatically contains this feature.

2 = add a new file in the root of the project called jsconfig.json

3 = Now add this code

{
   "exclude": ["node_modules"]
}

Happy coding (:

I also had the same problem: Visual Studio Code (v. 1.45.1) not adding imports automatically for one of my typescript projects. In my case, the problem was project specific and no extensions had to be added to VS Code.

Fix:

  1. Add "importHelpers": true to the compileOptions section of the tsconfig.json file.
  2. Restart VS Code.

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
...
  },

There is a Visual Studio Code issue you can track and thumbs up for this feature. There was also a User Voice issue , but I believe they moved voting to GitHub issues.

It seems they want auto import functionality in TypeScript, so it can be reused. TypeScript auto import issue to track and thumbs up here .

我正在使用 Devin Abbott 的“ImportJS”插件进行自动导入,您可以使用以下代码安装它

npm install --global import-js

VScode 1.57 (May 2021) reminds us of the (now) native auto import feature, and... improves it:

Completions in import statements

Auto import in JavaScript and TypeScript automatically add imports when you accept a suggestion.

With VS Code 1.57, they now also work when writing an import statement itself:

在导入语句中自动导入 -- https://media.githubusercontent.com/media/microsoft/vscode-docs/3e7e9293475f03a5263084d659f9dea6bf06dcc4/release-notes/images/1_57/ts-import.gif

This can be a time saver if you ever need to manually add an import.

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