The best way to run npm install for nested folders?

前端 未结 9 1858
北恋
北恋 2020-11-30 17:38

What is the most correct way to install npm packages in nested sub folders?

my-app
  /my-sub-module
  package.json
package.json
<
9条回答
  •  情歌与酒
    2020-11-30 18:34

    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.

    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'
        });
    })
    

    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).

    As suggested, you could also achieve the same thing with a bash script.

    EDIT: Made the code work in Windows

提交回复
热议问题