是否可以从 Node 脚本 运行 package.json 脚本?
Is it possible to run package.json scripts from a Node script?
我的 package.json 中有几个任务,例如:
"scripts": {
"test": "jest",
"test:ci": "jest --runInBand --no-cache --watch false --coverage true",
"test:codecov": "codecov",
"tsc:check": "tsc --noEmit",
"prettier:check": "pretty-quick --staged"
.
.
. // a lot more here
}
我正在尝试构建一个依赖于这些任务的构建脚本,但是在 package.json
中将其作为新脚本编写太冗长且难以阅读。
有什么方法可以从 build.js
文件中 运行 这些脚本吗?这样我就可以 chain/redo 这些任务并得到一些错误处理。
基于@anh-nguyen 我做了这个关于如何能够做我想做的事情的初始原始结构我希望这对某人有所帮助。
请注意,我使用的是 shelljs 而不是 process
和 process.exec
,因为我已经将其作为依赖项,但您可以根据需要更改它们。
// tslint:disable:no-string-literal
const shell = require('shelljs');
const path = require('path');
const rootDir = process.cwd();
const distBundlesDir = path.join(rootDir, 'dist-bundles');
const objectWithRawScripts = require(path.join(rootDir, 'package.json')).scripts;
const packageScripts = {
build: objectWithRawScripts['build'],
prettierCheck: objectWithRawScripts['prettier:check'],
tscCheck: objectWithRawScripts['tsc:check'],
};
function runScript(scriptToRun) {
try {
shell.echo(`Running ${scriptToRun}`);
shell.exec(scriptToRun);
} catch (e) {
shell.echo('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
shell.echo(`there was an error with ${scriptToRun}`);
console.error(e);
shell.echo('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
return false;
}
return true;
}
shell.echo('Init Tasks');
runScript(packageScripts.prettierCheck);
runScript(packageScripts.tscCheck);
我的 package.json 中有几个任务,例如:
"scripts": {
"test": "jest",
"test:ci": "jest --runInBand --no-cache --watch false --coverage true",
"test:codecov": "codecov",
"tsc:check": "tsc --noEmit",
"prettier:check": "pretty-quick --staged"
.
.
. // a lot more here
}
我正在尝试构建一个依赖于这些任务的构建脚本,但是在 package.json
中将其作为新脚本编写太冗长且难以阅读。
有什么方法可以从 build.js
文件中 运行 这些脚本吗?这样我就可以 chain/redo 这些任务并得到一些错误处理。
基于@anh-nguyen
请注意,我使用的是 shelljs 而不是 process
和 process.exec
,因为我已经将其作为依赖项,但您可以根据需要更改它们。
// tslint:disable:no-string-literal
const shell = require('shelljs');
const path = require('path');
const rootDir = process.cwd();
const distBundlesDir = path.join(rootDir, 'dist-bundles');
const objectWithRawScripts = require(path.join(rootDir, 'package.json')).scripts;
const packageScripts = {
build: objectWithRawScripts['build'],
prettierCheck: objectWithRawScripts['prettier:check'],
tscCheck: objectWithRawScripts['tsc:check'],
};
function runScript(scriptToRun) {
try {
shell.echo(`Running ${scriptToRun}`);
shell.exec(scriptToRun);
} catch (e) {
shell.echo('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
shell.echo(`there was an error with ${scriptToRun}`);
console.error(e);
shell.echo('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
return false;
}
return true;
}
shell.echo('Init Tasks');
runScript(packageScripts.prettierCheck);
runScript(packageScripts.tscCheck);