在嵌套子文件夹中安装npm packages
的最正确方法是什么?
my-app
/my-sub-module
package.json
package.json
packages
/my-sub-module
中npm install
运行后,my-app
<my-app></my-app>
的最佳方法是什么?
答案 0 :(得分:198)
如果您知道嵌套subdir的名称,我更喜欢使用post-install。在package.json
:
"scripts": {
"postinstall": "cd nested_dir && npm install",
...
}
答案 1 :(得分:18)
如果要运行单个命令在嵌套子文件夹中安装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脚本实现同样的目的。
编辑:使代码在Windows中运行
答案 2 :(得分:17)
我的解决方案非常相似。 Pure Node.js
以下脚本检查所有子文件夹(递归),只要它们具有package.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))
}
答案 3 :(得分:6)
仅供参考,以防人们遇到此问题。您现在可以:
npm install --save path/to/my/subfolder
答案 4 :(得分:5)
如果您的系统上有find
实用程序,则可以尝试在应用程序根目录中运行以下命令:
find . ! -path "*/node_modules/*" -name "package.json" -execdir npm install \;
基本上,找到所有package.json
个文件并在该目录中运行npm install
,跳过所有node_modules
目录。
答案 5 :(得分:3)
将Windows支持添加到snozza's回复
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' })
})
答案 6 :(得分:3)
根据@Scott的回答,只要知道子目录名称,install | postinstall脚本是最简单的方法。这就是我为多个子目录运行它的方式。例如,假设我们在monorepo根目录中有api/
,web/
和shared/
个子项目:
// In monorepo root package.json
{
...
"scripts": {
"postinstall": "(cd api && npm install); (cd web && npm install); (cd shared && npm install)"
},
}
答案 7 :(得分:3)
接受的答案有效,但您可以使用 --prefix
在选定位置运行 npm 命令。
"postinstall": "npm --prefix ./nested_dir install"
并且 --prefix
适用于任何 npm 命令,而不仅仅是 install
。
您还可以使用
查看当前前缀npm prefix
并设置您的全局安装 (-g) 文件夹
npm config set prefix "folder_path"
也许是 TMI,但你懂的...
答案 8 :(得分:1)
我更喜欢将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:*"
}
答案 9 :(得分:0)
受此处提供的脚本的启发,我构建了一个可配置的示例,
yarn
或npm
yarn
,但是目录只有package-lock.json
,它将为此使用npm
目录(默认为true)。cp.spawn
并行运行安装yarn 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 })
答案 10 :(得分:0)
find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c "cd '{}' && npm install" \;
答案 11 :(得分:0)
有些答案很旧。我认为,如今我们可以使用一些新选项来设置monorepos。
工作区是一种设置软件包体系结构的新方法,默认情况下从Yarn 1.0开始可用。它允许您以多种方式设置多个软件包,而只需运行一次
yarn install
就可以一次安装所有软件包。
Lerna是用于优化使用git和npm管理多包存储库的工作流程的工具。
lerna在纱线工作区也很完美-article。我刚刚完成了一个monorepo项目-example。
这是一个配置为使用npm + lerna-MDC Web的多包项目的示例:它们使用package.json的lerna bootstrap
运行postinstall
。
答案 12 :(得分:0)
[对于 macOS、Linux 用户]:
我创建了一个 bash 文件来安装项目和嵌套文件夹中的所有依赖项。
find . -name node_modules -prune -o -name package.json -execdir npm install \;
说明: 在根目录中,排除 node_modules
文件夹(甚至在嵌套文件夹中),找到包含 package.json
文件的目录,然后运行 {{1 }} 命令。
如果您只想在指定的文件夹(例如:abc123、def456 文件夹)上查找,请执行以下操作:
npm install