在嵌套子文件夹中安装npm包的最正确方法是什么?

my-app
  /my-sub-module
  package.json
package.json

当npm install在my-app中运行时,在/my-sub-module中自动安装包的最佳方法是什么?


当前回答

我的解决方案非常相似。 纯粹的node . js

下面的脚本检查所有子文件夹(递归地),只要它们有包。Json,并在每个文件中运行NPM install。 我们可以为它添加例外:允许没有package.json的文件夹。在下面的例子中,一个这样的文件夹是“packages”。 可以将其作为“预安装”脚本运行。

const path = require('path')
const fs = require('fs')
const child_process = require('child_process')

const root = process.cwd()
npm_install_recursive(root)

// Since this script is intended to be run as a "preinstall" command,
// it will do `npm install` automatically inside the root folder in the end.
console.log('===================================================================')
console.log(`Performing "npm install" inside root folder`)
console.log('===================================================================')

// Recurses into a folder
function npm_install_recursive(folder)
{
    const has_package_json = fs.existsSync(path.join(folder, 'package.json'))

    // Abort if there's no `package.json` in this folder and it's not a "packages" folder
    if (!has_package_json && path.basename(folder) !== 'packages')
    {
        return
    }

    // If there is `package.json` in this folder then perform `npm install`.
    //
    // Since this script is intended to be run as a "preinstall" command,
    // skip the root folder, because it will be `npm install`ed in the end.
    // Hence the `folder !== root` condition.
    //
    if (has_package_json && folder !== root)
    {
        console.log('===================================================================')
        console.log(`Performing "npm install" inside ${folder === root ? 'root folder' : './' + path.relative(root, folder)}`)
        console.log('===================================================================')

        npm_install(folder)
    }

    // Recurse into subfolders
    for (let subfolder of subfolders(folder))
    {
        npm_install_recursive(subfolder)
    }
}

// Performs `npm install`
function npm_install(where)
{
    child_process.execSync('npm install', { cwd: where, env: process.env, stdio: 'inherit' })
}

// Lists subfolders in a folder
function subfolders(folder)
{
    return fs.readdirSync(folder)
        .filter(subfolder => fs.statSync(path.join(folder, subfolder)).isDirectory())
        .filter(subfolder => subfolder !== 'node_modules' && subfolder[0] !== '.')
        .map(subfolder => path.join(folder, subfolder))
}

其他回答

我的解决方案非常相似。 纯粹的node . js

下面的脚本检查所有子文件夹(递归地),只要它们有包。Json,并在每个文件中运行NPM install。 我们可以为它添加例外:允许没有package.json的文件夹。在下面的例子中,一个这样的文件夹是“packages”。 可以将其作为“预安装”脚本运行。

const path = require('path')
const fs = require('fs')
const child_process = require('child_process')

const root = process.cwd()
npm_install_recursive(root)

// Since this script is intended to be run as a "preinstall" command,
// it will do `npm install` automatically inside the root folder in the end.
console.log('===================================================================')
console.log(`Performing "npm install" inside root folder`)
console.log('===================================================================')

// Recurses into a folder
function npm_install_recursive(folder)
{
    const has_package_json = fs.existsSync(path.join(folder, 'package.json'))

    // Abort if there's no `package.json` in this folder and it's not a "packages" folder
    if (!has_package_json && path.basename(folder) !== 'packages')
    {
        return
    }

    // If there is `package.json` in this folder then perform `npm install`.
    //
    // Since this script is intended to be run as a "preinstall" command,
    // skip the root folder, because it will be `npm install`ed in the end.
    // Hence the `folder !== root` condition.
    //
    if (has_package_json && folder !== root)
    {
        console.log('===================================================================')
        console.log(`Performing "npm install" inside ${folder === root ? 'root folder' : './' + path.relative(root, folder)}`)
        console.log('===================================================================')

        npm_install(folder)
    }

    // Recurse into subfolders
    for (let subfolder of subfolders(folder))
    {
        npm_install_recursive(subfolder)
    }
}

// Performs `npm install`
function npm_install(where)
{
    child_process.execSync('npm install', { cwd: where, env: process.env, stdio: 'inherit' })
}

// Lists subfolders in a folder
function subfolders(folder)
{
    return fs.readdirSync(folder)
        .filter(subfolder => fs.statSync(path.join(folder, subfolder)).isDirectory())
        .filter(subfolder => subfolder !== 'node_modules' && subfolder[0] !== '.')
        .map(subfolder => path.join(folder, subfolder))
}

添加Windows支持snozza的答案,以及跳过node_modules文件夹如果存在。

var fs = require('fs')
var resolve = require('path').resolve
var join = require('path').join
var cp = require('child_process')

// 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 (!mod === 'node_modules' && !fs.existsSync(join(modPath, 'package.json'))) return

    // Determine OS and set command accordingly
    const cmd = /^win/.test(process.platform) ? 'npm.cmd' : 'npm';

    // install folder
    cp.spawn(cmd, ['i'], { env: process.env, cwd: modPath, stdio: 'inherit' })
})

用例1:如果你想在每个子目录中运行npm命令(每个包。Json是),你将需要使用postinstall。

因为我经常使用npm-run-all,我用它来保持它的美观和简短(在postinstall的部分):

{
    "install:demo": "cd projects/demo && npm install",
    "install:design": "cd projects/design && npm install",
    "install:utils": "cd projects/utils && npm install",

    "postinstall": "run-p install:*"
}

这有一个额外的好处,我可以一次性安装,或单独安装。如果你不需要这个或者不希望npm-run-all作为依赖项,请查看demisx的答案(在postinstall中使用subshell)。

用例2:如果你将从根目录运行所有的npm命令(并且,例如,不会在子目录中使用npm脚本),你可以简单地安装每个子目录,就像你安装任何依赖一样:

npm install path/to/any/directory/with/a/package-json

在后一种情况下,如果您找不到任何node_modules或package-lock,请不要感到惊讶。所有的包都将安装在根目录node_modules中,这就是为什么你不能从你的任何子目录运行你的NPM命令(需要依赖)。

如果您不确定,用例1总是有效的。

如果你在你的系统上找到了实用程序,你可以尝试在你的应用程序根目录下运行以下命令: 找到。! -path "*/node_modules/*" -name "包。-execdir NPM install \;

基本上,找到所有的包。Json文件,并在该目录下运行NPM install,跳过所有node_modules目录。

find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c "cd '{}' && npm install" \;