首页 > 解决方案 > 是否可以从 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文件中运行这些脚本吗?所以我可以链接/重做这些任务,也可以得到一些错误处理。

标签: node.jsnpmnpm-scripts

解决方案


根据@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);

推荐阅读