将 node_modules 安装到供应商 [英] Install node_modules to vendor
问题描述
如何在本地为每个项目安装 npm 模块到 vendor/node_modules
并使 package.json
文件看到它们.
How can I install npm modules locally for each project to vendor/node_modules
and make package.json
file see them.
我不想将 package.json 移动到供应商文件夹
我有 bower 并且在 .bowerrc
中指定了 bower_components
路径 - 这非常简单.
I have bower and in .bowerrc
I specify the bower_components
path - that is super easy.
我如何使用 npm 做到这一点?
How can I do that with npm ?
我已经阅读了文档、npmrc 文档、这里的一些问题、谷歌搜索、浪费了一个多小时 - 仍然没有运气.对于这么简单的任务来说,这太难了.
I`ve read the docs, npmrc docs, some questions here, googled, wasted more than an hour - still no luck. This is ridiculously hard for such an easy task.
我不在乎缺点,只要最后告诉我怎么做就行了.
I don't care about minuses, just tell me how to do that finally.
推荐答案
对于安装到任意子文件夹中的 node_modules
文件夹似乎没有内置方法这一事实感到沮丧,我来了使用以下两个脚本找到一个偷偷摸摸的解决方案:
Frustrated by the fact that there seems to be no built in way to install into a node_modules
folder in an arbitrary subfolder, I came up with a sneaky solution using the two following scripts:
preinstall.js
var fs = require("fs");
try
{
fs.mkdirSync("./app/node_modules/");
}
catch(e)
{
}
try
{
if(process.platform.indexOf("win32") !== -1)
{
fs.symlinkSync("./app/node_modules/","./node_modules/","junction");
}
else
{
fs.symlinkSync("./app/node_modules/","./node_modules","dir");
}
}
catch(e){}
postinstall.js
var fs = require("fs");
try
{
if(process.platform.indexOf("win32") !== -1)
{
fs.unlinkSync("./node_modules/");
}
else
{
fs.unlinkSync("./node_modules");
}
}
catch(e){}
您需要做的就是在 package.json
文件中使用它们,方法是将它们添加到 scripts
选项:
All you need to do is use them in your package.json
file by adding them to the scripts
option:
"scripts": {
"preinstall": "node preinstall.js",
"postinstall": "node postinstall.js"
},
那么,最大的问题是:它有什么作用?
So, the big question is: what does it do?
好吧,当您调用
npm install
时,preinstall.js
脚本会触发,它会在您想要的子文件夹中创建一个node_modules
.然后它从npm
期望的node_modules
创建一个symlink
或(Windows 中的shortcut
)到真正的>node_modules
.
Well, when you call
npm install
thepreinstall.js
script fires which creates anode_modules
in the subfolder you want. Then it creates asymlink
or (shortcut
in Windows) from thenode_modules
thatnpm
expects to the realnode_modules
.
然后 npm
安装所有依赖项.
Then npm
installs all the dependencies.
最后,一旦安装了所有依赖项,postinstall.js
脚本就会触发,从而删除 symlink
!
Finally, once all the dependencies are installed, the postinstall.js
script fires which removes the symlink
!
这是一个方便的gist,包含您需要的一切.
Here's a handy gist with all that you need.
这篇关于将 node_modules 安装到供应商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!