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){}
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?
Well, when you call npm install
the preinstall.js
script fires which creates a node_modules
in the subfolder you want. Then it creates a symlink
or (shortcut
in Windows) from the node_modules
that npm
expects to the real node_modules
.
Then npm
installs all the dependencies.
Finally, once all the dependencies are installed, the postinstall.js
script fires which removes the symlink
!
Here's a handy gist with all that you need.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…