Npm init не работает в visual studio code
The text was updated successfully, but these errors were encountered:
endrik2700 commented Feb 22, 2019
Well, can someone help me!?
Tyriar commented Mar 2, 2019
What OS are you on? If you're getting this message it means that npm is not on the PATH.
endrik2700 commented Mar 3, 2019 •
Windows 10, it has worked in the VSC before. Probably the update messed something up. I can't even get my debugger to work in VSC: "type": "node",
"request": "launch",
"name": "Launch Program",
"program": "$"
>, standardised setting based on the support page. previously this worked, they were kind of deleted, typed in manually and it gives me a weird error message, cannot launch . on desktop, setting the *outFiles attribute might help. Umm deleted the file, nnow it seems working, but the terminal is locked on a different codecademy project instead and I think it wanna debug this. What an idiotical software
Tyriar commented Mar 5, 2019
Does it fix itself if you close all VS Code windows and open them again? (the environment doesn't refresh without a full restart)
Can you check your PATH environment variable in the terminal and see whether the npm path is missing? This is echo %PATH% if you're using cmd.exe
endrik2700 commented Mar 8, 2019
That's the result: %PATH%
Tried to install jquery in vsc with npm install. Says, it doesn't find the package.json
Tyriar commented Mar 8, 2019
@endrik2700 if you're using powershell I think you use $env:path
endrik2700 commented Mar 8, 2019
PS C:\Users\endri> $env:path
C:\Program Files (x86)\Intel\iCLS Client;C:\Program Files\Intel\iCLS Client;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin;C:\Program Files\Common Files\Intel\WirelessCommon;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files (x86)\IDEMIA\AWP\Dlls;C:\Program Files\IDEMIA\AWP\Dlls;C:\Program Files\nodejs;C:\Users\endri\AppData\Local\Microsoft\WindowsApps;;C:\Users\endri\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\endri\AppData\Roaming\npm
Tyriar commented Mar 8, 2019
Where is npm installed and does the directory show up in the path you just pasted in?
endrik2700 commented Mar 8, 2019
Should be global. Sent an order via the terminal: npm install --save npm-install-global. Saw errors couldn't find package.json.
Tyriar commented Mar 31, 2019
npm must be on your path in order for it to be runnable in a terminal, this is an issue related to your environment/setup that you'll need to investigate yourself.
Tyriar added the *question Issue represents a question, should be posted to StackOverflow (VS Code) label Mar 31, 2019
needs more info Issue requires more information from poster *question Issue represents a question, should be posted to StackOverflow (VS Code) terminal Integrated terminal issues
Нода установлена в wsl.
Если скрипт набирать и запускать ручками, то все работает, но если я этот же скрипт запускаю из блока npm scripts (то есть, которые vs code сам подтянул), то возникает ошибка:
The terminal process "C:\WINDOWS\System32\wsl.exe - e npm run start" failed to launch (exit code: 1)
Можно ли как-то это решить?
Простой 5 комментариев
WbICHA, как причём? в vs code я работаю, и из консоли, которая открыта в нем, я пытаюсь запустить npm скрипты, которые есть в проекте, только не набирая их - так всё работает, а запуском их из окна "npm scripts" - так быстрее, чтобы не набирать. Не очень понял, что вас смущает.
Pisht, и какое же отношение консоль имеет к вскоду? Когда у тебя что-то в приложении на винде не работает ты жалуешься на винду или приложение?
К тому же, у тебя из под всл вскод работает или через винду?
Чего? Какое ещё окно "npm scripts"? Это? А сам вскод тут причём? Не работает плагин, который последний раз обновлялся 3 года назад.
Короче, учись пользоваться консолью и не страдай фигнёй.
WbICHA, понял, что помочь по проблемы Вы вряд ли сможете, но ок, давайте я пропишу базовые вещи.
Консоль (терминал) можно открыть непосредственно в vs code. Об этом здесь
Если приложение предоставляет возможность работать с той или иной вещью, но при этом должным образом не работает, я жалуюсь на приложение. Если бы нода была установлена на винде (а не в подсистеме wsl, как сейчас) уверен, что скрипты бы из vs code запускались (то есть, в ваших категориях: vs code нормально бы работал с тем, что во вне).
Vs code стоит на винде.
В vs code интегрированы различные системы сборки, об этом здесь. В частности, vs code подтягивает npm скрипты из проекта, которые можно запустить в один клик - просто нажав на название нужного скрипта в окне npm scripts. Кстати, на странице плагина, который вы упомянули, об этом сказано - что теперь данный функционал доступен в самом редакторе.
Pisht, прошу прощения, но других советчиков я здесь не вижу, так что выбирать не приходится.
Что же касается того, что я не могу помочь, то через вскод на всл я уже больше года работаю, но мне очень лень разбираться в деталях.
Функционал консоли никоим образом не зависит от приложения, которое её запускает. Вскод просто открывает указанную консоль, будь то командная строка, павершел, баш или что-то другое.
Более того, а ты вообще уверен, что ты используешь баш в вскоде?
Упустил этот момент, благодарю за уточнение, упустил этот момент в патчноутах.
Так вот, исходя из всей инфы, что я здесь увидел, я делаю вывод, что ты запускаешь виндовсовскую версию вскода.
Открой баш в папке проекта и введи code . (или воспользуйся одним из этих методов), запусти скрипт.
Если не запустится, значит у тебя нода на всл не установлена.
После можешь в настройки добавить:
Тогда скрипты смогут и на виндовсовской версии запускаться, но лучше полностью уйти с неё на всл версию, она быстрее.
В любом случае можно выполнить команду npm в коде Visual Studio (используя f1 в > ) в Windows (10) для установки пакетов в мою папку, в которой я работаю ?
У меня установлен npm, и мне по-прежнему приходится устанавливать пакеты npm из cmd
Установить
- Ctrl + P , напишите ext install npm script runner
- Перезапустите VS Code
Используйте (двумя способами)
- Ctrl + R Shift + R
- Ctrl + P , введите >npm , выберите run script , выберите нужную задачу
Обновление . Начиная с версии 1.3 в коде Visual Studio встроен терминал. Чтобы открыть его, используйте любой из этих методов:
- Используйте сочетание клавиш Ctrl + ` .
- Используйте вид | Переключить команду меню встроенного терминала.
- В палитре команд ( Ctrl + Shift + P ) используйте View:Toggle Integrated Terminal команда.
Вы можете запускать команды npm непосредственно в терминале (ctrl + `). Убедитесь, что в качестве оболочки выбран терминал cmd.exe.
Вы можете использовать cmd.exe по умолчанию в качестве оболочки, выполнив следующие действия.
-
Ctrl + Shift + р
- Введите> Выберите Shell по умолчанию + Enter
- Выберите> Командная строка . cmd.exe
- Перезапустите VS Code.
Одна из причин может заключаться в том, что вы устанавливаете узел после запуска кода vs, поскольку встроенный или внешний терминал vs кода принимает значение пути, которое было во время запуска кода vs, и выдает ошибку:
Простой перезапуск кода vs решит проблему.
Все, что вам нужно сделать, это добавить аргументы во встроенный терминал в окне «Настройки пользователя».
Для этого выполните следующие действия:
- Элемент списка
- Перейдите в "Настройки пользователя"
- Поиск параметра с именем - "Terminal.integrated.shellArgs.windows"
- Измените этот параметр, скопировав его на правую сторону.
- Добавьте следующее значение arg = "/k nodevars.bat", например "terminal.integrated.shellArgs.windows": ["/k nodevars.bat"],
- Убедитесь, что для параметра с именем «Terminal.integrated.shell.windows» задано значение «C: \ Windows \ system32 \ cmd.exe». Если нет, то сделайте это.
- Откройте новый терминал.
На Win10 мне пришлось запускать VSCode от имени администратора для работы команд npm.
Чтобы установить npm на VS Code:
- Нажмите Ctrl + P
- Напишите программу запуска ext install npm
- В списке результатов найдите npm 'команды npm для кода VS'. Этот npm управляет командами. Нажмите «Установить», затем «Обновить код VS», чтобы сохранить изменения
- Перезапустите VS Code
- На встроенном терминале запустите 'npm install'
Доступно расширение, npm Script runner . Я сам не пробовал.
Я установил npm после кода Visual Studio, закрыл все экземпляры Visual Studio, снова открыл и он начал работать.
Похожие вопросы
Популярные теги
Is there anyway of executing the npm command within Visual Studio Code (using f1 into > ) on Windows(10) to install packages to my folder I'm working in?
I have npm installed and I keep having to install npm packages from cmd
22 Answers 22
Install
- Ctrl + P , write ext install npm script runner
- Restart VS Code
Use (two ways)
- Ctrl + R Shift + R
- Ctrl + P , write >npm , select run script , select the desired task
Update: Since version 1.3 Visual Studio Code has integrated terminal. To open it, use any of these methods:
- Use the Ctrl + ` keyboard shortcut.
- Use the View | Toggle Integrated Terminal menu command.
- From the Command Palette ( Ctrl + Shift + P ), use the View:Toggle Integrated Terminal command.
Please give a link to the extension from the market. I did not find such an extension. It does not exist.
@dev-siberia there is no need of any extension since the 1.3 version. Just follow the instructions described in the answer for the update. Ctrl + `
Note: if you're launching VS Code from the Anaconda Navigator, you'll need to restart the navigator as well.
You can run npm commands directly in terminal (ctrl + `). Make sure that terminal has cmd.exe as the shell selected.
You can default cmd.exe as your shell by following these steps.
- ctrl+Shift+p
- Type > Select Default Shell + Enter
- Select > Command Prompt . cmd.exe
- Restart VS Code.
even though I've installed several exenstions now, which I though would force npm to come along for the ride.. this tip didn't work for me. All I got: 'npm' is not recognized as an internal or external command, operable program or batch file.
Ok.. I don't even have Node.js installed. Per this article I'm realizing that's my first step, as it's not automatically installed w/VS Code
There might be a chance that you have install node.js while your visual studio code was open. Once node.js is install successfully, Simply close the VS Code and Start it again. It will work. Thank you
NOTE restart the application not reload window . At least as of VSC 1.31.1, this is true. Though this answer states restart the application I expected to be able to get this fixed through a reload window .
On Win10 I had to run VSCode as administrator to npm commands work.
All you need to do is to add args to the integrated terminal within 'User Settings' window.
Follow this steps below to do that:
- List item
- Go to 'User Settings'
- Search for setting named - "terminal.integrated.shellArgs.windows"
- Edit this setting by copying it to the right side.
- Add the following arg value = "/k nodevars.bat", e.g. "terminal.integrated.shellArgs.windows": ["/k nodevars.bat"],
- Make sure that the setting named "terminal.integrated.shell.windows" is set to the value - "C:\Windows\system32\cmd.exe". If not then do that.
- Open new Terminal.
I installed npm after Visual studio code, closed all visual studio instances and opened again and it started working.
One reason might be if you install the node after starting the vs code,as vs code terminal integrated or external takes the path value which was at the time of starting the vs code and gives you error:
'node' is not recognized as an internal or external command,operable program or batch file.
A simple restart of vs code will solve the issue.
To install npm on VS Code:
- Click Ctrl+P
- Write ext install npm script runner
- On the results list look for npm 'npm commands for VS Code'. This npm manages commands. Click Install, then Reload VS Code to save changes
- Restart VS Code
- On the Integrated Terminal, Run 'npm install'
does not work for me ! VSCode Terminal keeps saying bash: np: command not found . What do you suggest ? Thanks for any help on this. (Hint: My npm cmds work well under the Mac Terminal. But they absolutely do not work under VSCode Terminal - not even after having followed your steps above.) I try to run Angular cmds such as np version and they do not work in VSCode Terminal. And I am on Mac. Any idea why ?
Same thing was happening to me after I installed Node.js. Node and npm was recognized in PowerShell and Command Prompt but not in VS Code. I fixed it by adding the Node.js install path to the system's environment PATH variable. The node.js install path on my system was:
Where I find the node.exe that is needed. The user's PATH variable already had the Node.js install path but for some reason VS Code needs the Node.js install path in the system's PATH variables.
Windows 10 instructions:
- Windows key and type "environment"
- Select "Edit the system environment variables"
- Click button labelled "Environment Variables. "
- In "System variables" section edit the "Path" variable
- Add Node.js install path to the list (C:\Program Files\nodejs)
The other answers were great but this is another way to fix it that worked for me without needing to install stuff, run as admin, or change the default settings.
VSCode User Setup is a new installer which installs VSCode and its dependencies in directories which don't require system-level / administrator permissions to modify. This is because New VSCode runs with user privileges. Your Nodejs installation added npm's path as System variable which VSCode cannot read.
Adding NPM path to Path variable in the User variable, you will be able to run NPM from the integrated command line.
Try to install PowerShell extension provided by VS code.
After install click on PowerShell and It will start new PowerShell Console where you can run all script
Make sure you exit out of the existing terminal window. It will try to recover it and even though you may have closed out of VS Code you want to close the terminal window as well
Well, anyone still ends up here, and couldn't resolve the problem, Here is how to fix it.
Check the default terminal in VS Code (ctrl+ ~). It should be cmd and not Powershell.
If it is Powershell, go to settings > features > Terminal › Integrated › Default Profile: Windows. And select Command Prompt. Or in search settings type 'default profile', and select Command Prompt.
Install VS Code extension - npm script runner (npm support for VS Code by Microsoft). Click on extensions marketplace (ctrl + shift + x). Type> npm script runner > install
After these steps, npm should be working from VS Code terminal.
There is an extension available, npm Script runner . I have not tried it myself, though.
As an alternative to some of the answers suggested above, if you have powershell installed, you can invoke that directly as your terminal. That is edit the corresponding setting.json value as follows:
I find this works well as the environment is correctly configured.
Open standard terminal ctrl+p and paste this command
Need to see this logs npm should be run outside of the node repl, in your normal shell. (Press Control-D to exit.)
(To exit, press ^C again or type .exit)
C:\DW\Examples\Ang.Crud>npm i script-runner npm WARN saveError ENOENT: no such file or directory, open 'C:\DW\Examples\Ang.Crud\package.json' npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN enoent ENOENT: no such file or directory, open 'C:\DW\Examples\Ang.Crud\package.json' npm WARN Ang.Crud No description npm WARN Ang.Crud No repository field. npm WARN Ang.Crud No README data npm WARN Ang.Crud No license field.
- script-runner@0.1.8 added 7 packages from 5 contributors and audited 7 packages in 2.955s found 0 vulnerabilities
where is one of: access, adduser, audit, bin, bugs, c, cache, ci, cit, completion, config, create, ddp, dedupe, deprecate, dist-tag, docs, doctor, edit, explore, get, help, help-search, hook, i, init, install, install-test, it, link, list, ln, login, logout, ls, outdated, owner, pack, ping, prefix, profile, prune, publish, rb, rebuild, repo, restart, root, run, run-script, s, se, search, set, shrinkwrap, star, stars, start, stop, t, team, test, token, tst, un, uninstall, unpublish, unstar, up, update, v, version, view, whoami
npm -h quick help on npm -l display full usage info npm help search for help on npm help npm involved overview
Specify configs in the ini-formatted file: C:\Users\fdc.npmrc or on the command line via: npm --key value Config info can be viewed via: npm help config
Please tell me how i can solve it. Iam using window 7 32 bit:
11 Answers 11
this worked for me, simply put my vscode was using bash instead of cmd prompt. interesting it flipped from cmd to bash after an install which caught me off guard
The switching shells helped me. Make sure to restart VS code too if you had it opened during the install or it still won't work!
This answer helped me, except Ctrl+Shift+P didn't work for me (on mac). Instead I was able to switch by doing this: 1. In menu choose Terminal > New Terminal. 2. Click the plus (+) symbol at the top of the new terminal which next to the word "bash" and change it to something other than "bash." In my case, "zsh."
This worked for me - except that there is no longer "Select Default Shell" in vscode anymore. There is "Select Default Profile". and then you can set it to either cmd or powershell and one other option
After following the steps, no matter how many times I restarted VScode, I did not get the issue resolved until I rebooted my machine.
By default, Visual Studio Code runs shell commands like npm in a loginless shell. If you installed NVM, Visual Studio Code may have no indication where to find npm to run it.
Put the following lines are in .bash_profile : (Note: Not .bashrc .)
Add this setting to settings.json :
Donno why this was downvoted, but this answer actually helped me with the same problem (ZSH instead of Bash) in Linux while migrating from VS Code to Codium.
@FelipeCenteno I'm guessing it has something to do with the "loginless shell" and the fact that .bashrc is a local config
I got this error after having just installed nodejs/npm, and the way i resolved, while still being able to use git bash terminal in vscode was to simply restart my computer (I hadn't done this after node installation).
Ha! Thank you! This worked! node and npm were working in terminals outside vscode but for some reason not in VSCode's internal terminal, I restarted and they work!
The config for my bash terminal 'inside vscode' hasn't changed (default setting) and I tried this and it worked. I should've dive into this at first, oh my one hour.
On Mac OS , I switched to the zsh and got this fixed. These following steps fixed the issue :
- On your VsCode in Mac : shift + command + P .
- On the Prompt > type : Terminal: Select Default Profile , then "Click it". Note, as you type you will find this option in the auto-complete .
- Click the option for zsh or your desired shell.
- Restart VSCode .
now npm will work in your vscode terminal.
Same on Linux. And completely restarting VSCode is actually necessary, Ctrl+Shift+P → Reload window is not enough. We can show this by adding for instance echo $(date) started >> /home/
I needed to kill the terminal in VS Code and restart a new terminal to get npm to show as installed.
Of course, this would be like the 14th or 15th thing I would try to get it to work. Nevermind the reinstall, reboot, and changing environment PATH variables. LOL, Thanks.
On mac, I switched the default shell from bash to zsh and it fixed the issue.
OP is using Windows 7 for which zsh is not available. Please refrain from posting "answers" that in no way help in solving the issue.
I'm gonna add an answer just for help others because this question is 2 years old.
If you can run the npm start (NPM SCRIPTS below the Explorer view) but you are not able to launch the command with a shortcut: Then check npm extension is installed and/or enabled for the current workspace/folder.
Otherwise vsCode will not be able to run the script and you're going to get a message in a little box like this
Maybe the NPM Scripts View below the explorer is not available without the plugin I'm not sure
Читайте также: