Лучший способ запустить npm install для вложенных папок?
каков наиболее правильный способ установки npm packages во вложенных подпапках?
my-app
/my-sub-module
package.json
package.json
что это лучший способ иметь packages на /my-sub-module устанавливается автоматически, когда npm install выполнить в my-app?
4 ответов:
если вы хотите запустить одну команду для установки пакетов npm во вложенных подпапках, вы можете запустить скрипт через
npmи главноеpackage.jsonв корневом каталоге. Скрипт посетит каждый подкаталог и запуститnpm install.ниже
.jsскрипт, который позволит достичь желаемого результата: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файлы).как и предполагалось, вы также можете достичь того же с помощью сценария bash.
EDIT: сделал код работать в Windows
Я предпочитаю использовать после установки, если вы знаете имена вложенных подкаталогов. В
package.json:"scripts": { "postinstall": "cd nested_dir && npm install", ... }
мое решение очень похожа. Чистый Узел.js
следующий скрипт проверяет все подпапки (рекурсивно), пока они имеют
package.jsonи работаетnpm installв каждом из них. К нему можно добавить исключения: разрешенные папки не имеющиеpackage.json. В приведенном ниже примере одной из таких папок является "пакеты". Можно запустить его как сценарий "предустановки".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 это ответ
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 (!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' }) })
Comments