简体   繁体   中英

Is it possible to run package.json scripts from a Node script?

I have several task in my package.json like:

"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
}

I am trying to build a build script that depends on those tasks but write it as a new script in package.json is too verbose and hard to read.

Is there some way to run those scripts from a build.js file? so I can chain/redo those tasks and also get some error handling.

Based on @anh-nguyen comment I did this initial raw structure on how to be able to do what I wanted I hope this helps somebody.

Notice that instead of process and process.exec I am using shelljs because I already had it as dependency but you could change them if needed.

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM