在 WSL2 中: Ubuntu 20.04 for Windows 10 nodejs 已安装,但 npm 不工作

In WSL2: Ubuntu 20.04 for Windows 10 nodejs is installed but npm is not working

我在我的 Windows 10 操作系统中使用 WSL2: Ubuntu 20.04。我已经使用命令 sudo apt-get install -y nodejs 安装了 nodejs 当我执行 node -v 命令时我得到 v12.18.3

mrd@DESKTOP-2EO5K4H:/mnt/c/Users/musfi$ node -v
v12.18.3

但是当我执行npm -v命令时,我在命令

下面得到了这个
mrd@DESKTOP-2EO5K4H:/mnt/c/Users/musfi$ npm -v
-bash: /mnt/c/Program Files/nodejs/npm: /bin/sh^M: bad interpreter: No such file or directory

我也执行whereis命令。希望这将有助于找到解决方案。

mrd@DESKTOP-2EO5K4H:/mnt/c/Users/musfi$ whereis node
node: /usr/bin/node /usr/include/node /mnt/c/Program Files/nodejs/node.exe /usr/share/man/man1/node.1.gz

mrd@DESKTOP-2EO5K4H:/mnt/c/Users/musfi$ whereis npm
npm: /usr/bin/npm /mnt/c/Program Files/nodejs/npm /mnt/c/Program Files/nodejs/npm.cmd /usr/share/man/man1/npm.1

我已经尝试了几乎所有的 Whosebug 解决方案和 github 问题,但没有任何效果。
希望任何善良的灵魂都能解决这个问题。提前致谢。

试试这个

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
sudo apt install npm

对于所有 Unix/Linux/MacOS 操作系统,我总是宁愿使用“节点版本管理器”。它通常可以在 Linux 和 MacOS 上完美运行(也有一个 Windows 端口),并且能够以非常简单的方式正确安装 nodenpm,而不需要root.

看这里:https://github.com/nvm-sh/nvm

我可以在我的机器上确认它也适用于 Ubuntu 20.04 on WSL2。

以下错误的解决方法: -bash: /mnt/c/Program Files/nodejs/npm: /bin/sh^M: bad interpreter: No such file or directory

编辑~/.bashrc 在文件末尾追加:

# strip out problematic Windows %PATH%
PATH=$(echo "$PATH" | sed -e 's/:\/mnt.*//g')

现在 npm init 可以工作了。

更好的方法是在您的 Windows 用户目录中配置 /etc/wsl.conf

将此添加到 /etc/wsl.conf 中,因此 Windows 路径不会优先

[interop]
appendWindowsPath=false

有关更多配置详细信息,请查看 Microsoft 开发人员博客 here