问题描述
在嵌套子文件夹中安装npm packages
的最正确方法是什么?
What is the most correct way to install npm packages
in nested sub folders?
my-app
/my-sub-module
package.json
package.json
在my-app
中运行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软件包安装在嵌套的子文件夹中,则可以通过root中的npm
和主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的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!