【问题标题】:Is it possible to run package.json scripts from a Node script?是否可以从 Node 脚本运行 package.json 脚本?
【发布时间】:2019-01-23 17:34:05
【问题描述】:

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

【问题讨论】:

  • 您是否尝试在您的build.js 文件中运行npm run <script_name>
  • 否,但这不是有效的 javascript。
  • 正确,确实是 bash。您必须编写代码来运行脚本 bash const process = require('child_process'); process.exec('npm run ...')
  • 这实际上是个好主意@anh-nguyen。我会试试的!

标签: node.js npm npm-scripts


【解决方案1】:

基于@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);

【讨论】:

    猜你喜欢
    • 2016-11-07
    • 2020-11-08
    • 1970-01-01
    • 2014-04-09
    • 2023-01-05
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多