Automated Import Feature in Visual Studio Code

I'm currently transitioning from Webstorm to Visual Studio Code due to the poor performance of Webstorm.

However, I'm facing issues with Visual Studio Code not being very efficient at detecting and importing the dependencies I need. I find myself manually searching for them, which is quite time-consuming. I'd rather endure a 15-second wait in Webstorm for it to handle imports automatically than having to do it manually in Visual Studio Code.

https://i.sstatic.net/pjeiN.png

The project I'm working on is based on the angular2 seed by @minko-gechev found at https://github.com/mgechev/angular2-seed

I have a tsconfig.json file in my base directory with the following setup:

    {
  "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
}

Additionally, there's another tsconfig.json file in my src/client directory configured as follows:

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

I'm unsure why there are two separate configurations. Since the angular seed project uses typescript gulp build tasks, the compilation process might differ.

Is there any way to enhance the efficiency of Visual Studio Code in this scenario?

Answer №1

In the current year 2018, there is no need for any extensions to enable auto-imports in JavaScript or TypeScript. By simply ensuring that you have checkjs: true in your jsconfig.json file, you can enjoy this feature.

There are two types of auto imports available: one is the "add missing import" quick fix, which appears as a lightbulb icon when errors occur:

https://code.visualstudio.com/docs/editor/editingevolved#_code-action

The other type is the auto import suggestions, which display suggested items as you type. You can also select text and press Ctrl + Space to bring up a list of suggestions. Accepting an auto import suggestion will automatically add the import at the top of the file.

https://code.visualstudio.com/Docs/languages/javascript#_auto-imports

Both functionalities should work seamlessly with JavaScript and TypeScript without requiring additional tools. If you encounter any issues with auto imports, feel free to report them here.

Answer №2

I managed to get everything up and running smoothly after installing a variety of helpful plugins listed below.

Usually, the classes import automatically as I type their names. If not, a lightbulb icon pops up for easy importing. Alternatively, pressing F1 and typing "import..." provides additional options. I find myself utilizing all these methods. Additionally, the F1 Implement feature for implementing interfaces is quite handy, although it may not work every time.

Recommended Plugins:

Check out this screenshot showcasing the installed extensions.

https://i.sstatic.net/JRS7Z.png
*click for full resolution

Answer №3

The configuration file tsconfig.app.json for a typical Angular 10 application includes:

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

After making a modification to the include section by adding TypeScript files as well:

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

This adjustment resolved my issue https://i.sstatic.net/aE7f5.png

Answer №4

I recently utilized the Auto Import tool created by steoates, and I found it to be incredibly user-friendly.

This plugin automatically identifies, processes, and offers code actions and suggestions for all available imports. It is compatible with both Typescript and TSX.

Answer №6

If you've come across this issue recently, I discovered that adding a specific setting was necessary in order for the auto-imports to function correctly using my workspace's version of TypeScript. To make this adjustment, simply insert the following line into your workspace settings:

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

Afterwards, when you have a TypeScript file open in VS Code, select the version number for TypeScript located at the bottom right corner of the screen. Once the options appear at the top, opt for "use workspace version" and then proceed to reload VS Code.

Following these steps, the auto-import feature should now be up and running smoothly.

Answer №7

I encountered a similar issue where Visual Studio Code (version 1.45.1) was not automatically adding imports for one of my TypeScript projects. Interestingly, the problem I faced was specific to that project and did not require any additional extensions in VS Code.

Solution:

  1. Include "importHelpers": true in the compileOptions section of the tsconfig.json file.
  2. Restart Visual Studio 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,
...
  },

Answer №8

Visual Studio Code now offers built-in support for this feature, but it appears to be a bit inconsistent in its functionality. From what I have gathered, VS Code needs to load necessary data for automatic imports in the following manner:

  • Retrieve data for all exports from your local files
  • Fetch data for all exports from node_modules/@types
  • Acquire data for all exports from node_modules/{packageName} only if any of your local files are importing them

You can find a more detailed explanation in this comment: https://github.com/microsoft/TypeScript/issues/31763#issuecomment-537226190.

However, due to potential bugs either within VS Code itself or in specific packages' type declarations, the last two steps may not always function as expected. In my case, I faced issues with auto-imports for react-bootstrap while working on a plain Create-React-App project. The workaround that worked for me was manually copying the package folder from node_modules to node_modules/@types and keeping only the type declaration files there, such as Button.d.ts. This is not an ideal solution since deleting the node_modules folder would require repeating this process. Nonetheless, I found it preferable to continually writing import statements manually.

Before resorting to this method, I had attempted and failed with the following approaches:

  • Updating VS Code to version 1.45.1
  • Installing types for the relevant package using command like
    npm install --save @types/react-bootstrap
  • Creating a jsconfig.json file and adjusting settings based on recommendations from others
  • Experimenting with various plugins for automated imports

Answer №9

Make sure to populate the include field within the initial level of the JSON-object in the tsconfig.editor.json as shown below:

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

This configuration has been effective for me.

If necessary, you can also incorporate additional TypeScript file extensions, such as:

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

Answer №10

Include the "typeRoots" property within the tsconfig.json file:

"typeRoots": [
      "node_modules/@types",
      "node_modules/@react",
      "node_modules/@react/router"
    ]

Feel free to append any additional paths as needed.

Answer №11

Make sure to review your tsconfig.json file for any errors if you are using Angular (check the problems terminal).

I encountered an issue where I mistakenly duplicated these lines, and it caused a problem with my code.

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

Answer №12

If you're working on a JavaScript project like ReactJs or React-Native, simply follow these steps:

  1. Start by removing all auto import plugins since VS Code already has this feature built-in.

  2. Create a new file named jsconfig.json in the root directory of your project.

  3. Next, add the following code to the jsconfig.json file:

    {
       "exclude": ["node_modules"]
    }
    

Answer №13

Encountered an issue while using Typescript Version 3.8.3.

Although Intellisense is a great tool, the auto-import feature was not functioning properly for me. Despite trying to install an extension, the problem persisted. After double-checking all extension settings, the solution was found in clearing the cache at

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

and reloading VSCode.

Note: To access AppData in username, enable the option to Show (Hidden Items) under the View menu.

Sometimes, confusion arises when we mistake import-related errors for issues with deprecated features or APIs in Angular.

For instance, attempting to use:

constructor(http: Http) {

//...}

When 'Http' has been replaced by 'HttpClient', this may lead to misinterpretation of errors as being related to auto-import failures. Additional information on deprecated APIs and Features can be found here.

Answer №14

Having Typescript Importer has been a game-changer for me

Check out the Typescript Importer here!

This tool goes above and beyond by searching for typescript definitions within your workspace and seamlessly importing them with just a press of the enter key.

Answer №15

If you're interested in the auto import feature for TypeScript in Visual Studio Code, there is a GitHub issue where you can track and show support by giving it a thumbs up. The User Voice issue related to this has been moved to GitHub as well.

To stay updated on the progress of auto import functionality in TypeScript, check out the TypeScript auto import GitHub issue and give it a thumbs up to show your interest!

Answer №16

Currently, I have been utilizing the 'ImportJS' plugin created by Devin Abbott for automatic importation, and you can easily set it up with the following code:

npm install --global import-js

Answer №17

Visual Studio Code version 1.57, released in May 2021, introduces an enhanced auto import feature that is now native to the software:

Improved Auto Imports

In JavaScript and TypeScript, auto imports automatically include necessary imports when you accept a suggestion.

With the latest update of VS Code 1.57, this feature extends to working within import statements themselves:

https://i.sstatic.net/6QEEM.gif

This improvement can save time for users who frequently need to manually add imports.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choosing the specific columns to be shown in the Kendo Angular grid

Will there be an interface available in the grid for users to select which columns are displayed, or is this a feature that will be introduced in the upcoming September release? ...

Can Angular i18n facilitate language switching?

My objective is to switch the language from English (United States) to Indonesia using a button. View Source Code https://i.sstatic.net/0YlfWaCY.gif The issue is that the tutorial does not cover how to implement the language change feature. Why opt for ...

Combining normal imports with top-level await: A guide

Is it possible to simultaneously use imports (import x from y) and top-level awaits with ts-node? I encountered an issue where changing my tsconfig.compilerOptions.module to es2017 or higher, as required by top-level awaits, resulted in the following error ...

What could be causing my NextJS application to not recognize the _document.tsx file?

Seeking assistance in understanding why my _document.tsx is not loading properly within my nextJS application. My Attempts So Far I have been diligently following the NextJS documentation for creating a custom _document.js. Despite my efforts, I am unable ...

A guide to adding a delay in the RxJS retry function

I am currently implementing the retry function with a delay in my code. My expectation is that the function will be called after a 1000ms delay, but for some reason it's not happening. Can anyone help me identify the error here? When I check the conso ...

Ways to sort mat-select in alphabetical order with conditional names in options

I am looking to alphabetically order a mat-select element in my Angular project. <mat-select [(ngModel)]="item" name="item" (selectionChange)="changeIdentificationOptions($event)"> <mat-option *ngFor="let item of items" [value]="item"> ...

Data from graphql is not being received in Next.js

I decided to replicate reddit using Next.js and incorporating stepzen for graphql integration. I have successfully directed it to a specific page based on the slug, but unfortunately, I am facing an issue with retrieving the post information. import { use ...

Prevent the array from altering its values

I am utilizing a mock-service that is configured in the following way: import { Article } from "./article"; export const ARTICLES: Article[] = [ new Article( 1, 'used', 5060639120949, 'Monster Energy& ...

Angular 10: A guide to dynamically highlighting navbar elements based on scrolling position

I am currently working on a single-page application using Angular 10. I have a simple page layout and I want to implement a feature that will highlight the navbar based on the scroll position. How can I achieve this functionality in a single-page applicati ...

Having trouble implementing the ternary operator (?) in TypeScript within a Next.js project

Trying to implement a ternary operator condition within my onClick event in a Next.js application. However, encountering an error indicating that the condition is not returning any value. Seeking assistance with resolving this issue... https://i.stack.img ...

Setting up the NPM configuration in Intellij IDEA for proxy in Angular 2

How can I set up Intellij IDEA to run an npm Angular 2 conf with a proxy as an argument by clicking on it? I know I can do it via the terminal using the command ng serve --proxy-config proxy.conf.json, but it would be much easier to configure it in Intelli ...

Top Tips for Layering Components in Angular 5

Just starting out with Angular, currently in the process of creating a sample website. Created a cover page component named <app-coverpage> and have additional components that I want to overlap the cover page as part of the background effect. All c ...

I'm curious as to why my array is only being filled within the subscription function

When I call the GetAllMainStore() function, data is successfully retrieved from the API and the console indicates that "this.MainStoreArray" contains data. The problem arises when I attempt to access "this.MainStoreArray" outside of the GetAllMainStore() ...

iOS 10.3.1 causing Ionic 2 (click) event to trigger twice

I am currently working on an Ionic 2 app and I am facing an issue with the click event. When I test the app on a device and click on a button, let's say to trigger an alert, the function executes once. However, if I click on the button again, the fun ...

A Step-by-Step Guide on Modifying the Default Button in Angular2CSV

I am currently utilizing Angular 4 along with the Angular2CSV plugin to transfer data from an Angular page to Microsoft Excel. The process has been successful thus far. However, I am interested in changing the name of the button but am unsure of how to d ...

Experience the convenience of selecting multiple rows with checkboxes, while enjoying the simplicity of selecting a single row by clicking

Hey there! I'm looking to enable multiple selection using checkboxes and single selection by clicking on a row. Does anyone know how I can achieve this within the same table? Check out this link for some ideas ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

Exploring Angular 2 with ng-bootstrap Library

As I delve into learning Angular2, my goal is to incorporate ng-bootstrap into my project. However, I have encountered issues when trying to import ng-bootstrap and create a functional project. Being a novice in this field, I am unsure if the problem lies ...

Transforming Bootstrap using Typescript styled components

I have been working on customizing the Navbar in my React app using Typescript's styled components. However, I am facing difficulties in restyling the default styles from Bootstrap that I have copied. Here is an example of the React Bootstrap Navbar c ...

Unlock the Power of Angular with Custom Decorators: Accessing ElementRef Made Easy

I am currently working on implementing a decorator for Host CSS Variable Binding in Angular5. However, I am facing difficulties in properly implementing it with the given code. Is there a way to define ElementRef from within the decorator itself? export f ...