node.js - 是否可以从 Node 脚本运行 package.json 脚本?
问题描述
我的 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
文件中运行这些脚本吗?所以我可以链接/重做这些任务,也可以得到一些错误处理。
解决方案
根据@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);
推荐阅读
- swagger - openapi-generator 生成器做反向
- python - PostgreSQL 查询帮助:如何检查多个列的值是否同时增加/减少
- java-8 - 如何创建一个以集合对象为值的 KStream?
- javascript - 如何让我的网站记住哪个 CTA 被按下重定向
- java - 如果一个`changeSet`未能应用,如何回滚`databaseChangeLog`中的所有`changeSet`?
- python - Python Matplotlib - MFCC:X 轴固定为 2?
- java - 根据两个键值从 Firebase 数据库获取值
- php - 抓取页面脚本突然停止工作
- google-apps-script - 使用 GAS,能够更新对表单的响应?
- git - 公共存储库时应该包含什么 .gitignore 文件?