Skip to content

Instantly share code, notes, and snippets.

@justan
Last active October 10, 2023 03:53
Show Gist options
  • Save justan/78316953b6d1ad0ad90a9e39e29f6aab to your computer and use it in GitHub Desktop.
Save justan/78316953b6d1ad0ad90a9e39e29f6aab to your computer and use it in GitHub Desktop.
run turbo/yarn workspace command by path
import { execSync } from 'child_process';
import pt from 'path';
import os from 'os';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const rawCommand = process.argv[2];
const argv = process.argv.slice(3);
const args = argv.slice();
const action = args.shift();
let command;
if (rawCommand === 'r') {
let isArgs = false;
const packageNames = [];
const commandArgs = [];
args.forEach((p) => {
if (p.startsWith('-')) {
isArgs = true;
}
if (isArgs) {
commandArgs.push(p);
} else {
try {
packageNames.push(require(pt.join(process.cwd(), p, 'package.json')).name);
} catch (e) {
console.warn(e.message);
}
}
});
if (packageNames.length === 0) {
console.error(`目录 ${args} 不是有效的 package`);
process.exit(1);
}
command = `${os.type() === 'Windows_NT' ? '%npm_execpath%' : '$npm_execpath'} run ${action} ${packageNames
.map((name) => `--filter=${name}`)
.join(' ')} ${commandArgs.join(' ')}`;
} else {
const packagePath = args.shift();
command = `yarn workspace ${
require(pt.join(process.cwd(), packagePath, 'package.json')).name
} run ${action} ${args.join(' ')}`;
}
console.log('执行:', command);
execSync(command, { stdio: 'inherit' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment