为嵌套文件夹运行npm install的最佳方法? [英] The best way to run npm install for nested folders?

查看:95
本文介绍了为嵌套文件夹运行npm install的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在嵌套子文件夹中安装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的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆