Який найправильніший спосіб встановити npm packagesвкладені підпапки?
my-app
/my-sub-module
package.json
package.json
Що таке найкращий спосіб бути packagesв /my-sub-moduleвстановлюється автоматично при npm installзапуску в my-app?
Який найправильніший спосіб встановити npm packagesвкладені підпапки?
my-app
/my-sub-module
package.json
package.json
Що таке найкращий спосіб бути packagesв /my-sub-moduleвстановлюється автоматично при npm installзапуску в my-app?
Відповіді:
Якщо ви хочете виконати одну команду для встановлення пакетів npm у вкладені папки, ви можете запустити скрипт через npmта main 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-сценарієм.
РЕДАКТУВАННЯ: Код змушений працювати в Windows
Я вважаю за краще використовувати пост-інсталяцію, якщо ви знаєте імена вкладеного піддіректора. В package.json:
"scripts": {
"postinstall": "cd nested_dir && npm install",
...
}
"postinstall": "cd nested_dir2 && npm install"для кожної папки?
За відповіддю @ Скотта, скрипт install | postinstall є найпростішим способом, доки відомі імена підкаталогів. Ось як я запускаю його для декількох підказок. Наприклад, зробіть вигляд, що у нас є api/, web/і shared/підпроекти в корені монорепо:
// In monorepo root package.json
{
...
"scripts": {
"postinstall": "(cd api && npm install); (cd web && npm install); (cd shared && npm install)"
},
}
( )для створення підшаровок і уникання cd api && npm install && cd ...
npm installна вищому рівні:"(cd was unexpected at this time."
Моє рішення дуже схоже. Чистий Node.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))
}
Тільки для довідки, якщо люди стикаються з цим питанням. Тепер ви можете:
npm install --save path/to/my/subfolder
mkdir -p a/b ; cd a ; npm init ; cd b ; npm init ; npm install --save through2 ;Тепер зачекайте ... ви просто встановили вручну залежності в "b", це не те, що відбувається, коли ви клонуєте новий проект. rm -rf node_modules ; cd .. ; npm install --save ./b. Тепер перелічіть node_modules, потім список b.
Використовуйте випадок 1 : Якщо ви хочете мати можливість виконувати npm-команди з кожного підкаталогу (де кожен package.json є), вам потрібно буде використовувати postinstall.
Оскільки я часто використовую npm-run-allвсе-таки, я використовую його, щоб він був красивим і коротким (частина в післяінсталяції):
{
"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 (використовуючи підзаголовки в постінсталяції).
Використовуйте випадок 2 : Якщо ви будете виконувати всі команди npm з кореневого каталогу (і, наприклад, не будете використовувати сценарії npm у підкаталогах), ви можете просто встановити кожен підкаталог, як і будь-яка залежність:
npm install path/to/any/directory/with/a/package-json
В останньому випадку не дивуйтеся, що ви не знайдете жодного node_modulesабо package-lock.jsonфайлу в підкаталогах - всі пакети будуть встановлені в корені node_modules, і тому ви не зможете запускати npm-команди (що вимагати залежностей) від будь-якого з ваших підкаталогів.
Якщо ви не впевнені, використання випадку 1 завжди працює.
run-pне потрібно, але це тоді більш багатослівно"postinstall": "npm run install:a && npm run install:b"
&&без run-p. Але, як ви кажете, це менш читабельно. Інший недолік (який run-p вирішує, оскільки встановлення працює паралельно) полягає в тому, що якщо один не вдасться, жоден інший скрипт не вплине
Додавання підтримки 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' })
})
Надихнувшись наданими тут скриптами, я створив приклад, який можна настроїти:
yarnабоnpmyarnале у каталозі є лише вона, package-lock.jsonвона буде використовуватись npmдля цього каталогу (за замовчуванням - true).cp.spawnyarn workspaces(налаштовується)const path = require('path');
const { promises: fs } = require('fs');
const cp = require('child_process');
// if you want to have it automatically run based upon
// process.cwd()
const AUTO_RUN = Boolean(process.env.RI_AUTO_RUN);
/**
* Creates a config object from environment variables which can then be
* overriden if executing via its exported function (config as second arg)
*/
const getConfig = (config = {}) => ({
// we want to use yarn by default but RI_USE_YARN=false will
// use npm instead
useYarn: process.env.RI_USE_YARN !== 'false',
// should we handle yarn workspaces? if this is true (default)
// then we will stop recursing if a package.json has the "workspaces"
// property and we will allow `yarn` to do its thing.
yarnWorkspaces: process.env.RI_YARN_WORKSPACES !== 'false',
// if truthy, will run extra checks to see if there is a package-lock.json
// or yarn.lock file in a given directory and use that installer if so.
detectLockFiles: process.env.RI_DETECT_LOCK_FILES !== 'false',
// what kind of logging should be done on the spawned processes?
// if this exists and it is not errors it will log everything
// otherwise it will only log stderr and spawn errors
log: process.env.RI_LOG || 'errors',
// max depth to recurse?
maxDepth: process.env.RI_MAX_DEPTH || Infinity,
// do not install at the root directory?
ignoreRoot: Boolean(process.env.RI_IGNORE_ROOT),
// an array (or comma separated string for env var) of directories
// to skip while recursing. if array, can pass functions which
// return a boolean after receiving the dir path and fs.Dirent args
// @see https://nodejs.org/api/fs.html#fs_class_fs_dirent
skipDirectories: process.env.RI_SKIP_DIRS
? process.env.RI_SKIP_DIRS.split(',').map(str => str.trim())
: undefined,
// just run through and log the actions that would be taken?
dry: Boolean(process.env.RI_DRY_RUN),
...config
});
function handleSpawnedProcess(dir, log, proc) {
return new Promise((resolve, reject) => {
proc.on('error', error => {
console.log(`
----------------
[RI] | [ERROR] | Failed to Spawn Process
- Path: ${dir}
- Reason: ${error.message}
----------------
`);
reject(error);
});
if (log) {
proc.stderr.on('data', data => {
console.error(`[RI] | [${dir}] | ${data}`);
});
}
if (log && log !== 'errors') {
proc.stdout.on('data', data => {
console.log(`[RI] | [${dir}] | ${data}`);
});
}
proc.on('close', code => {
if (log && log !== 'errors') {
console.log(`
----------------
[RI] | [COMPLETE] | Spawned Process Closed
- Path: ${dir}
- Code: ${code}
----------------
`);
}
if (code === 0) {
resolve();
} else {
reject(
new Error(
`[RI] | [ERROR] | [${dir}] | failed to install with exit code ${code}`
)
);
}
});
});
}
async function recurseDirectory(rootDir, config) {
const {
useYarn,
yarnWorkspaces,
detectLockFiles,
log,
maxDepth,
ignoreRoot,
skipDirectories,
dry
} = config;
const installPromises = [];
function install(cmd, folder, relativeDir) {
const proc = cp.spawn(cmd, ['install'], {
cwd: folder,
env: process.env
});
installPromises.push(handleSpawnedProcess(relativeDir, log, proc));
}
function shouldSkipFile(filePath, file) {
if (!file.isDirectory() || file.name === 'node_modules') {
return true;
}
if (!skipDirectories) {
return false;
}
return skipDirectories.some(check =>
typeof check === 'function' ? check(filePath, file) : check === file.name
);
}
async function getInstallCommand(folder) {
let cmd = useYarn ? 'yarn' : 'npm';
if (detectLockFiles) {
const [hasYarnLock, hasPackageLock] = await Promise.all([
fs
.readFile(path.join(folder, 'yarn.lock'))
.then(() => true)
.catch(() => false),
fs
.readFile(path.join(folder, 'package-lock.json'))
.then(() => true)
.catch(() => false)
]);
if (cmd === 'yarn' && !hasYarnLock && hasPackageLock) {
cmd = 'npm';
} else if (cmd === 'npm' && !hasPackageLock && hasYarnLock) {
cmd = 'yarn';
}
}
return cmd;
}
async function installRecursively(folder, depth = 0) {
if (dry || (log && log !== 'errors')) {
console.log('[RI] | Check Directory --> ', folder);
}
let pkg;
if (folder !== rootDir || !ignoreRoot) {
try {
// Check if package.json exists, if it doesnt this will error and move on
pkg = JSON.parse(await fs.readFile(path.join(folder, 'package.json')));
// get the command that we should use. if lock checking is enabled it will
// also determine what installer to use based on the available lock files
const cmd = await getInstallCommand(folder);
const relativeDir = `${path.basename(rootDir)} -> ./${path.relative(
rootDir,
folder
)}`;
if (dry || (log && log !== 'errors')) {
console.log(
`[RI] | Performing (${cmd} install) at path "${relativeDir}"`
);
}
if (!dry) {
install(cmd, folder, relativeDir);
}
} catch {
// do nothing when error caught as it simply indicates package.json likely doesnt
// exist.
}
}
if (
depth >= maxDepth ||
(pkg && useYarn && yarnWorkspaces && pkg.workspaces)
) {
// if we have reached maxDepth or if our package.json in the current directory
// contains yarn workspaces then we use yarn for installing then this is the last
// directory we will attempt to install.
return;
}
const files = await fs.readdir(folder, { withFileTypes: true });
return Promise.all(
files.map(file => {
const filePath = path.join(folder, file.name);
return shouldSkipFile(filePath, file)
? undefined
: installRecursively(filePath, depth + 1);
})
);
}
await installRecursively(rootDir);
await Promise.all(installPromises);
}
async function startRecursiveInstall(directories, _config) {
const config = getConfig(_config);
const promise = Array.isArray(directories)
? Promise.all(directories.map(rootDir => recurseDirectory(rootDir, config)))
: recurseDirectory(directories, config);
await promise;
}
if (AUTO_RUN) {
startRecursiveInstall(process.cwd());
}
module.exports = startRecursiveInstall;
І з ним використовується:
const installRecursively = require('./recursive-install');
installRecursively(process.cwd(), { dry: true })
Якщо у вас є findутиліта у вашій системі, ви можете спробувати виконати таку команду у кореневому каталозі програми:
find . ! -path "*/node_modules/*" -name "package.json" -execdir npm install \;
В основному, знайдіть усі package.jsonфайли та запустіть npm installу цьому каталозі, пропустивши всі node_modulesкаталоги.
find . ! -path "*/node_modules/*" ! -path "*/additional_path/*" -name "package.json" -execdir npm install \;