是否有删除所有全局npm模块的命令?如果没有,你有什么建议?


当前回答

对于Windows,这个脚本可以用来核化本地和用户的全局模块和缓存。

我注意到在linux上,全局根对系统来说是全局的,而不是给定的用户。因此,对于共享系统,删除全局根可能不是一个好主意。除此之外,如果有兴趣,我可以将脚本移植到bash。

对于Windows,保存到一个cmd文件中运行。

@ECHO OFF
SETLOCAL EnableDelayedExpansion 
SETLOCAL EnableExtensions

SET /A ecode=0

:: verify
SET /P conf="About to delete all global and local npm modules and clear the npm cache. Continue (y/[n])?
IF /I NOT "%conf%"=="y" (
  ECHO operation aborted
  SET /A ecode=!ecode!+1
  GOTO END
)

:: wipe global and local npm root
FOR %%a IN ("" "-g") DO (

  :: get root path into var
  SET cmd=npm root %%~a
  FOR /f "usebackq tokens=*" %%r IN (`!cmd!`) DO (SET npm_root=%%r)

  :: paranoid
  ECHO validating module path "!npm_root!"
  IF "!npm_root:~-12!"=="node_modules" (
    IF NOT EXIST "!npm_root!" (
      ECHO npm root does not exist "!npm_root!"
    ) ELSE (
      ECHO deleting "!npm_root!" ...
      :: delete
      RMDIR /S /Q "!npm_root!"
    )
  ) ELSE (
      ECHO suspicious npm root, ignoring "!npm_root!"
  )
)

:: clear the cache
ECHO clearing the npm cache ...
call npm cache clean

:: done
ECHO done

:END

ENDLOCAL & EXIT /b %ecode%

其他回答

下面是我尝试的一个更优雅的解决方案,我让npm为我做所有的工作。

# On Linux Mint 19.1 Cinnamon
# First navigate to where your global packages are installed.

$ npm root # returns /where/your/node_modules/folder/is
$ cd /where/your/node_modules/folder/is # i.e for me it was cd /home/user/.npm-packages/lib/node_modules

然后,如果你进行npm卸载或npm删除,这些模块将被视为正常的项目依赖项。它甚至生成一个包锁。Json文件,当它完成:

$ npm remove <package-name> # you may need sudo if it was installed using sudo  

使用此代码卸载任何包:

npm rm -g <package_name>

如果你有MSYS for Windows:

rm -rf ${APPDATA//\\/\/}/npm

对于Windows,这个脚本可以用来核化本地和用户的全局模块和缓存。

我注意到在linux上,全局根对系统来说是全局的,而不是给定的用户。因此,对于共享系统,删除全局根可能不是一个好主意。除此之外,如果有兴趣,我可以将脚本移植到bash。

对于Windows,保存到一个cmd文件中运行。

@ECHO OFF
SETLOCAL EnableDelayedExpansion 
SETLOCAL EnableExtensions

SET /A ecode=0

:: verify
SET /P conf="About to delete all global and local npm modules and clear the npm cache. Continue (y/[n])?
IF /I NOT "%conf%"=="y" (
  ECHO operation aborted
  SET /A ecode=!ecode!+1
  GOTO END
)

:: wipe global and local npm root
FOR %%a IN ("" "-g") DO (

  :: get root path into var
  SET cmd=npm root %%~a
  FOR /f "usebackq tokens=*" %%r IN (`!cmd!`) DO (SET npm_root=%%r)

  :: paranoid
  ECHO validating module path "!npm_root!"
  IF "!npm_root:~-12!"=="node_modules" (
    IF NOT EXIST "!npm_root!" (
      ECHO npm root does not exist "!npm_root!"
    ) ELSE (
      ECHO deleting "!npm_root!" ...
      :: delete
      RMDIR /S /Q "!npm_root!"
    )
  ) ELSE (
      ECHO suspicious npm root, ignoring "!npm_root!"
  )
)

:: clear the cache
ECHO clearing the npm cache ...
call npm cache clean

:: done
ECHO done

:END

ENDLOCAL & EXIT /b %ecode%

对于那些使用Windows的人来说,删除所有全局安装的npm包的最简单的方法是删除以下内容:

C:\用户\用户名\应用数据\漫游\npm

您可以通过在资源管理器、运行提示符或开始菜单中键入%appdata%/npm快速到达那里。