是否可以在项目之间共享node_modules目录

tuv*_*kki 4 node.js gulp

我的项目设置如下:

workspace
?cache
  ?node_modules
    ?gulp (and gulp-plugins, express etc.)
?nodejs
  ?node.exe
?project1
  ?gulpfile.js
?project2
  ?gulpfile.js
Run Code Online (Sandbox Code Playgroud)

现在我想在项目目录中执行gulpfile:

set NODE_PATH='C:\workspace\cache\node_modules\'
cd C:\workspace\project1\
C:\workspace\nodejs\node.exe C:\workspace\cache\node_modules\gulp\bin\gulp.js watch
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

[12:06:04] Local gulp not found in C:\workspace\project1
[12:06:04] Try running: npm install gulp
Run Code Online (Sandbox Code Playgroud)

在两个项目文件夹中,gulpfile都是类似的,并使用了一组类似的插件.我真的希望只有一次依赖项(因为我可能有多达25个项目共享相同的node_modules).这种设置是否可行,或者单独的项目目录是否需要拥有自己的node_modules文件夹?

ddp*_*rrt 6

Gulp要求您同时拥有全局安装和本地安装.所以你需要将Gulp相对于你的Gulpfile.如果您package.json将设在workspace和你的node_modules将是workspace/node_modules一切都正常工作,因为节点的搜索树的,但如果你不能移动它们,只有这样才能使它的工作是"假"的node_modules文件夹.

您可以通过创建符号链接来完成此操作.

这是在Unix/Linux/Mac上:

ln -s ../cache/node_modules node_modules
Run Code Online (Sandbox Code Playgroud)

这是在Windows上

mklink /D node_modules ../cache/node_modules
Run Code Online (Sandbox Code Playgroud)

(后者可能会有所不同,我不是在Win机器上)

  • 实际上,您不需要全局安装 gulp,您只需要在命令行工具中使用它即可。我使用的命令(带有 node.exe 和 gulp.js 的完整路径)是为了防止必须使用全局安装的 gulp。此方法适用于 Windows 上的以下 createlink 命令: `mklink /J node_modules ..\SFBC\node_modules` 记录;我的头撞在桌子上,因为我自己没有想到这一点。来自 Linux/Mac 环境,我没有使用相同的方法在 Windows 中应用。 (2认同)