- Код Visual Studio — автоматический импорт / быстрое исправление не работает
- 1 ответ
- Visual Studio Code — Auto Imports / Quick Fix does not work
- 1 Answer 1
- Auto import (and import fix) for React components #66122
- Comments
- jabacchetta commented Jan 7, 2019 •
- Autoimport not working #2473
- Comments
- asdine commented Apr 25, 2019
- tj commented Apr 25, 2019
- huguesalary commented Apr 25, 2019
- csprl commented Apr 25, 2019
- dkqkx commented Apr 25, 2019
- huguesalary commented Apr 25, 2019
- stamblerre commented Apr 25, 2019
- stamblerre commented Apr 25, 2019
- huguesalary commented Apr 25, 2019
- stamblerre commented Apr 25, 2019
- huguesalary commented Apr 25, 2019
- stamblerre commented Apr 25, 2019
- huguesalary commented Apr 25, 2019
- Hawken94 commented Apr 26, 2019
- jellevandenhooff said,
- ramya-rao-a commented Apr 30, 2019
- huguesalary commented Apr 30, 2019
- zephinzer commented Apr 30, 2019
- stamblerre commented Apr 30, 2019
- ramya-rao-a commented Apr 30, 2019
- vscode will not auto import node modules packages correctly #30472
- Comments
- dantman commented Jan 19, 2019
- Steps to reproduce
- What should happen
- What actually happens
- mjbvz commented Mar 18, 2019 •
- RyanCavanaugh commented Mar 19, 2019
- dantman commented Mar 19, 2019 •
- RyanCavanaugh commented Mar 19, 2019
- dantman commented Mar 19, 2019
Код 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 начнет работать для этой библиотеки.
Источник
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.
Источник
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
Источник
vscode will not auto import node modules packages correctly #30472
Comments
dantman commented Jan 19, 2019
There was a similar issue to this in the past. However this is NOT a duplicate. The old issue was fixed with an upgrade to TypeScript 3.x and/or adding «baseUrl»: «.» . However this issue happens under TypeScript 3.2.2 and adding «baseUrl»: «.» does not fix it.
I disabled all my extensions and tested the same thing in the latest Insiders release. It still exists.
Steps to reproduce
- Open a new folder workspace
- Use the following package.json
- npm install
- Save the following to jsconfig.json
- Use your intellisense keybinding (usually Ctrl+Space) after @decorate to autocomplete decorate with the function from core-decorators.
What should happen
The line added should simply import core-decorators .
What actually happens
The import line uses a relative ( .. ) path to the node_modules folder.
If you modify jsconfig.json to add «baseUrl»: «.» to compilerOptions the path will instead start with node_modules.
VS Code version: Code 1.30.2 (61122f88f0bf01e2ac16bdb9e1bc4571755f5bd8, 2019-01-07T22:48:31.260Z)
OS version: Darwin x64 18.2.0
System Info
Item | Value |
---|---|
CPUs | Intel(R) Core(TM) i5-7267U CPU @ 3.10GHz (4 x 3100) |
GPU Status | 2d_canvas: enabled checker_imaging: disabled_off flash_3d: enabled flash_stage3d: enabled flash_stage3d_baseline: enabled gpu_compositing: enabled multiple_raster_threads: enabled_on native_gpu_memory_buffers: enabled rasterization: enabled video_decode: enabled video_encode: enabled webgl: enabled webgl2: enabled |
Load (avg) | 6, 4, 3 |
Memory (System) | 16.00GB (0.71GB free) |
Process Argv | -psn_0_53261 |
Screen Reader | no |
VM | 0% |
Extensions: none
The text was updated successfully, but these errors were encountered:
mjbvz commented Mar 18, 2019 •
Tested with TS 3.4.0-dev.20190316
This seems related to using «target»: «esnext» / «module»: «es2015» in the jsconfig. It works for for «module»: «commonjs» .
Here’s a git repo with example project: https://github.com/mjbvz/ts-30472
RyanCavanaugh commented Mar 19, 2019
I’m inclined to say this is working as intended. The ES2015 module system doesn’t specify that a bare name foo should resolve to a spine-located folder node_modules/foo — only CommonJS does. If you actually are using a file-based ES2015 module resolver, then the only correct path is the relative form ../node_modules/core-decorators
dantman commented Mar 19, 2019 •
@RyanCavanaugh The ES2015 module system also does not say that the «main» from package.json should be looked up, that «.js» extensions can be stripped, or that a folder can have an «index.js» file.
So if you are really going with browser paths then ../node_modules/core-decorators and node_modules/core-decorators/index are both still wrong, as in a browser the only path that will work is ../node_modules/core-decorators/index.js .
So clearly TypeScript is still going by file loader semantics.
The ES2015 module system doesn’t specify that a bare name foo should resolve to a spine-located folder node_modules/foo — only CommonJS does.
This is also incorrect. CommonJS modules do not specify that bare modules come from a node_modules folder (or that a package.json main is to be read). CommonJS modules were not created by Node.js, we use node_modules because Node’s implementation details became the de-facto standard for module resolution.
So currently this is definitely not working as intended. The paths are incorrect for plain es2015/browser imports. And they are also incorrect for Node style imports. And using module: commonjs/es2015 doesn’t tell you what module resolution style is being used because neither es2015 modules nor commonjs modules specify the path to the bare module as node_modules .
I would recommend defaulting to assuming Node.js style lookups. Because clearly other parts of typescript/vscode are already assuming that.
If you want to support relative browser style imports, then you’ll need to add another property to specify what module lookup style is being used (url, commonjs (optional, with another property to define the conceptual namespace root), node style (includes node_modules as the root and package.json lookup)).
RyanCavanaugh commented Mar 19, 2019
I would recommend defaulting to assuming Node.js style lookups
module: commonjs is the default! You have to manually specify a different module target to change this, which you did, and TypeScript took you at your word and stopped assuming that node_modules was something that could be looked up.
CommonJS modules do not specify that bare modules come from a node_modules folder
CommonJS is understood by TS to be «CommonJS as implemented by the overwhelmingly predominant CJS resolve, Node, which uses node_modules as a lookup location» because we do have to fill in the gaps of the «Unspecified» part of that wiki page.
dantman commented Mar 19, 2019
module: commonjs is the default! You have to manually specify a different module target to change this, which you did, and TypeScript took you at your word and stopped assuming that node_modules was something that could be looked up.
I meant defaulting to Node.js style path lookups in all module types. Use module to specify the file format/syntax, not the path lookup. Just about all the module syntaxes can be used with multiple path lookup patterns. And use a different property which defaults to node style imports to specify what module resolution pattern to use. e.g. «resolve-module»: «node» (default), «resolve-module»: «html» .
Please also take into account that currently Node.js style lookups is the default / widest used module resolution pattern for es2015. The first ever implementation IIRC was Babel which just transpiled to CommonJS and even when better implementations were implemented (WebPack, Rollup, ESM, etc) they used Node.js lookups. The browser style lookups in browsers were only implemented well after large amounts of of code were already in production using es2015 modules with Node.js style module resolution. And I expect it is still true today that the majority of TypeScript/vscode users are writing ES2015 importing code using a Node.js module resolution.
So honestly the default module resolution for es2015 is Node style module resolution. Also worth noting, you don’t even need a new property immediately for the vscode use case. vscode already has an «Input Module Specifier» setting that can be set to «relative» to force it to always use relative imports to node_modules which should make it compatible with browser imports. The majority of us who use Node.js module lookups however, don’t have that level of control because «auto» is already the default and is where this bug is being encountered.
Honestly this feels a bit strange. Neither CommonJS nor ECMAScript specify where bare imports come from (CommonJS leaves the «conceptual module namespace root» unspecified and ECMAScript makes puts the entire resolution algorithm into an implementation-defined HostResolveImportedModule). For CommonJS, TypeScript’s behaviour is to fill in the unspecified by assuming you are using the most common implementation (Node style module imports). But for ES2015, TypeScript’s behaviour is to fill in the unspecified portion by assuming you are not using the most common implementation and to spit out something that is not correct for any of the current implementations.
Источник