Vs code autoimport не работает

Visual Studio Code — Auto Imports / Quick Fix does not work

My VS Code does not auto-import stuff from node_modules .

I’ve tried to make it work on two PCs and one Mac — the result is the same: No suggestions to import as I type, no options when I focus on a symbol and pressing Ctrl+. / Cmd+. — no quick fix suggestions.

I tried to install Auto Import extension — no suggestions.

I read this release notes post about «Add all missing imports» and tried to apply the shortcut — no luck, it does not do anything.

Читайте также:  Что делать если беспроводной наушник не работает вместе

At this point I am completely lost, I see many posts where people ask the same and people suggest them to use Quick Fix by pressing Ctrl+. but as you can see on the screenshot — it does not have any suggestions.

I am using TypeScript but I also tried this with JS — no luck.

On the screenshot I am running my app in WSL but I also tried native run on both Windows and macOS.

Any ideas? Thanks!

1 Answer 1

It appears that until recently (before TypeScript 4 release) the only way to make auto-imports work was to import each library you need at least once in your project (does not matter where). After that VS Code supposed to start auto-import stuff from them.

Starting TS 4 the VS Code suppose to start doing it automatically (more concrete — auto-include from all the libraries specified in your package.json ), though I’ve noticed that it uses the wrong paths to the code while importing — to the /dist/ folders as opposed to whatever a library exposes. As a result, Node.js might not be able to resolve and execute them. I’ve created an issue here

Note that in order this to work at all

  • Make sure your VS Code uses TS 4.0.2 or greater (as shown in the bottom right corner, click it to change)
  • You may need to set setting typescript.preferences.includePackageJsonAutoImports to on , because it your imports list exceeds 10 dependencies — it may/won’t not scan them. See release notes for the details.

The bottom line — in order it to work correctly at the moment you still need to import (by hand) a new dependency in your code (anywhere) at least once and then VS Code auto-import will start working for that lib.

Источник

Код Visual Studio — автоматический импорт / быстрое исправление не работает

Мой код VS не импортирует файлы автоматически из node_modules .

Я пытался заставить его работать на двух ПК и одном Mac — результат тот же: нет предложений для импорта при вводе текста, нет параметров, когда я фокусируюсь на символе и нажимаю Ctrl+. / Cmd+. — нет предложений по быстрому исправлению.

Я попытался установить расширение Auto Import — предложений нет.

Я прочитал это сообщение о выпуске о» Добавить все отсутствующие импорты «и попытался применить ярлык — не повезло, он ничего не делает.

На данный момент я полностью потерялся, я вижу много сообщений, в которых люди спрашивают то же самое и предлагают им использовать Quick Fix, нажав Ctrl +. но как видно на скриншоте — предложений нет.

Я использую TypeScript, но я также пробовал это с JS — не повезло.

На скриншоте я запускаю свое приложение в WSL, но я также пробовал выполнять нативный запуск как в Windows, так и в macOS.

Любые идеи? Благодарность!

1 ответ

Похоже, что до недавнего времени (до выпуска TypeScript 4) единственным способом заставить автоматический импорт работать был импорт каждой библиотеки, которая вам нужна, хотя бы один раз в вашем проекте (неважно где). После этого VS Code должен был начать с них автоимпорт.

Начиная с TS 4, код VS предполагает, что он начинает делать это автоматически (более конкретно — автоматическое включение из всех библиотек, указанных в вашем package.json ), хотя я заметил, что он использует неправильные пути к коду при импорте — в папки / dist /, а не все, что предоставляет библиотека. В результате Node.js может оказаться не в состоянии разрешить и выполнить их. Я создал здесь проблему

Обратите внимание, что для того, чтобы это вообще работало

  • Убедитесь, что ваш VS Code использует TS 4.0.2 или выше (как показано в правом нижнем углу, щелкните его, чтобы изменить)
  • Возможно, вам потребуется установить для параметра typescript.preferences.includePackageJsonAutoImports значение on , потому что если ваш список импорта превышает 10 зависимостей — он может или не будет сканировать их. Подробнее см. в примечаниях к выпуску..

Итог — для того, чтобы он работал правильно в данный момент, вам все еще нужно импортировать (вручную) новую зависимость в вашем коде (где угодно) хотя бы один раз, а затем автоимпорт VS Code начнет работать для этой библиотеки.

Источник

Auto import (and import fix) for React components #66122

Comments

jabacchetta commented Jan 7, 2019 •

There are a few issues with importing React components:

1. Export not detected

Whether or not it’s detected appears to be a random occurrence from what I can tell. If this happens, opening the file first will fix the issue.

2. Can’t auto-import a nested component

It does not appear in the suggestion list. This appears to be an expected result, as described here, but I wonder if that should be changed/fixed. As shown below in my workflow, the limitation kills productivity.

Note that yes, you can first type in the opening bracket, which will bring up the suggestion, and then you can select the suggestion, and then you can type in the closing bracket and let VSCode’s auto closing tag feature kick in. However, that seems like a lot of unnecessary steps.

Optimally this would work more like an Emmet suggestion, as described here. We would be able to start typing in our component name immediately and then simply select the suggestion.

3. Import fix requires checkJs

Maybe not even a fix, but I’m curious, why does auto import work without any extra settings, yet, in order to get the import fix to show up in code actions, the following setting is required: «javascript.implicitProjectConfig.checkJs»: true ?

The text was updated successfully, but these errors were encountered:

Источник

Autoimport not working #2473

Comments

asdine commented Apr 25, 2019

Since version 0.10.0 (0.10.1 included), autoimport doesn’t work anymore.
This happens in a regular GOPATH as well as using go modules.

I am using Visual Studio Code Version: 1.33.1 on Ubuntu 18.04.2 LTS.
I have selected goimports in the settings, but it doesn’t work with goreturn either

The text was updated successfully, but these errors were encountered:

tj commented Apr 25, 2019

ditto, auto-import and auto-complete for unimported packages fail for me

huguesalary commented Apr 25, 2019

Both of those work for me when the gopls language server is disabled

csprl commented Apr 25, 2019

Yeah, it looks like it’s related to gopls. Disabling it (Settings -> Use Language Server) solved it for me too.

dkqkx commented Apr 25, 2019

try del «go.useLanguageServer» and reload goimports

huguesalary commented Apr 25, 2019

Looking into the vs-code source, and at the settings sections here’s what I gathered:

1- When using the language server ( gopls ), the format tools are disabled:

So, it makes sense that goimports won’t work.

2- Now, enabling the language server isn’t sufficient. It needs to be configured, and that part is not easily found in the documentation.

You need to make sure to use this configuration(from https://github.com/golang/go/wiki/gopls#editors-instructions) to get the auto-import feature back:

Now, unfortunately, on my end, using this configuration restores the import feature, but it breaks the autocompletetion, as seen here:

stamblerre commented Apr 25, 2019

For the goimports/gofmt behavior, you need to configure this setting:

stamblerre commented Apr 25, 2019

@huguesalary: imports should not be related to autocompletion. Does autocompletion work when you turn off the setting?

huguesalary commented Apr 25, 2019

@stamblerre The auto completion broke when I enabled the language server, but, disabling the language server did not bring back the auto-completion. Meanwhile, the reformatting also broke.

I’m totally unclear about what is going on.

stamblerre commented Apr 25, 2019

Can you confirm that the language server is running? Go to «View: Debug Console» -> «Output» tab -> «Tasks» drop down, and check that there is an item titled gopls . You should be able to see more debug information there. Remember that you have to reload VSCode every time you change language server settings.

huguesalary commented Apr 25, 2019

I figured it out.

The language server was correctly running.

The issue was that the autoimport feature imported github.com/Sirupsen/logrus (note the capital S ). This import in turn was breaking, all the go tools with an error go: github.com/Sirupsen/logrus@v1.4.1: parsing go.mod: unexpected module path «github.com/sirupsen/logrus»

This error was completely invisible as far as vscode is concerned. It simply was breaking, but not showing any information, not even in the debug console.

Fixing this import fixed my issue.

stamblerre commented Apr 25, 2019

Glad you were able to resolve your issue, and I’m sorry the errors weren’t showing up. We’re going to try and do a better job of showing errors to the user — you can track this on golang/go#31668.

huguesalary commented Apr 25, 2019

Oh, I don’t think the error reporting issue is a gopls one. I did get gopls errors in the console:

The issue, I think, was vscode not showing me at any moment the other error (and cause of everything else):

go: github.com/Sirupsen/logrus@v1.4.1: parsing go.mod: unexpected module path «github.com/sirupsen/logrus»

Hawken94 commented Apr 26, 2019

#2469 this issue has an solution.

jellevandenhooff said,

This happens to me both go.useLanguageServer and without. It started happening recently. It make autocompleteUnimportedPackages impossible to use. Reverting to 0.9.2 makes the problem disappear.

ramya-rao-a commented Apr 30, 2019

So to summarize,

  • When using gopls , adding of missing imports or removal of unused imports don’t work on file save until the setting regarding source.organizeImports is added.
    • I have updated our README regarding this
  • Auto import of unimported packages do not work anymore on auto-completion.
    • This is being tracked in #2469. Please see the comment #2469 (comment) for the fix
  • Importing of a wrong package broke all features of gopls
    • @huguesalary At this point, did VS Code show any error at all?
    • @stamblerre This is a situation where the language server fails to provide any feature I guess. We will need to think of the best way to notify users about this. I believe the middleware is where we can add something to check for rejected promise from the language service and then do something appropriate. Thoughts?

huguesalary commented Apr 30, 2019

@ramya-rao-a the only visible error was in the output tab of vscode, under the gopls selector.

And the error was:

zephinzer commented Apr 30, 2019

Same problem, switched back to 0.9.2 and it started working again

stamblerre commented Apr 30, 2019

@huguesalary and @zephinzer: do you mind each filing issues in https://github.com/golang/go/issues? I can help you debug it there.

ramya-rao-a commented Apr 30, 2019

In the latest beta version of this extension,

  • The source.organizeImports code action is enabled by default for Go files. So, no setting needs to be added to get missing imports or remove unused imports on file save when using gopls
  • Auto-import during auto-completion should be fixed as well.

If anyone is seeing issues after enabling gopls , please log a new issue at https://github.com/golang/go/issues, share any Go related settings you have and the logs from View -> Output -> gopls

Closing this issue as most of the concerns have been addressed. Please log new issues for the rest

Источник

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 have a tsconfig.json in my baseDir that looks like this:

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

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??

16 Answers 16

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:

Once I changed the include like to be:

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:

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.

For Javascript projects:

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

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/ only if any of your local files is importing them

Источник

Оцените статью