0

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.

4
  • Have you tried to just run npm run <script_name> in your build.js file? Commented Jan 23, 2019 at 8:49
  • No, but that is not valid javascript. Commented Jan 23, 2019 at 8:52
  • Correct, it's bash indeed. You have to write code to run script bash const process = require('child_process'); process.exec('npm run ...') Commented Jan 23, 2019 at 8:54
  • That is actually a good idea @anh-nguyen. I will try it! Commented Jan 23, 2019 at 8:56

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.