是否可以从Node脚本运行package.json脚本?

时间:2019-01-23 08:45:13

标签: node.js npm npm-scripts

我的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文件运行那些脚本?这样我就可以链接/重做这些任务,并获得一些错误处理。

1 个答案:

答案 0 :(得分:0)

基于@ anh-nguyen comment,我对如何完成自己想做的事情做了初步的构想,希望对大家有所帮助。

请注意,我使用的是shelljs,而不是processprocess.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);
相关问题