问题描述
在嵌套子文件夹中安装 npm 包
的最正确方法是什么?
What is the most correct way to install npm packages
in nested sub folders?
my-app
/my-sub-module
package.json
package.json
npm install
在 中运行时自动安装
?/my-sub-module
中的 packages
的最佳方法是什么?我的应用
What is the best way to have packages
in /my-sub-module
be installed automatically when npm install
run in my-app
?
推荐答案
如果你想运行一个命令来在嵌套的子文件夹中安装 npm 包,你可以通过 npm
和 main package.json
在您的根目录中.该脚本将访问每个子目录并运行 npm install
.
If you want to run a single command to install npm packages in nested subfolders, you can run a script via npm
and main package.json
in your root directory. The script will visit every subdirectory and run npm install
.
下面是一个 .js
脚本,它将达到预期的结果:
Below is a .js
script that will achieve the desired result:
var fs = require('fs');
var resolve = require('path').resolve;
var join = require('path').join;
var cp = require('child_process');
var os = require('os');
// get library path
var lib = resolve(__dirname, '../lib/');
fs.readdirSync(lib).forEach(function(mod) {
var modPath = join(lib, mod);
// ensure path has package.json
if (!fs.existsSync(join(modPath, 'package.json'))) {
return;
}
// npm binary based on OS
var npmCmd = os.platform().startsWith('win') ? 'npm.cmd' : 'npm';
// install folder
cp.spawn(npmCmd, ['i'], {
env: process.env,
cwd: modPath,
stdio: 'inherit'
});
})
请注意,这是从 StrongLoop 文章中获取的示例,该文章特别指出解决模块化 node.js
项目结构(包括嵌套组件和 package.json
文件).
Note that this is an example taken from a StrongLoop article that specifically addresses a modular node.js
project structure (including nested components and package.json
files).
按照建议,您也可以使用 bash 脚本实现相同的目的.
As suggested, you could also achieve the same thing with a bash script.
使代码在 Windows 中工作
Made the code work in Windows
这篇关于为嵌套文件夹运行 npm install 的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!