繁体   English   中英

"如何以编程方式执行“npm run”命令?"

[英]How to execute 'npm run' command programmatically?

我有一些自定义测试脚本,我可以使用npm run test<\/code>命令运行它,该命令执行一些用于启动 e2e\/单元测试的 Node 脚本。 但在此之前,我必须在其他终端窗口中使用npm run dev<\/code>启动 webpack dev 服务器(这也是一些自定义节点脚本,细节无关紧要)。 所以,我想省略npm run dev<\/code>手动执行并将其移动到自定义npm run test<\/code>脚本,即我想在 Node 脚本中以编程方式执行 webpack dev 服务器。 如何使用 Node 脚本以编程方式执行npm run dev<\/code>并停止它? 提前致谢!

"dev": "node node_modules/webpack-dev-server/bin/webpack-dev-server.js --host 0.0.0.0 --history-api-fallback --debug --inline --progress --config config/config.js"

您可以使用 exec 从脚本运行

import {series} from 'async';
const {exec} = require('child_process');

series([
 () => exec('npm run dev'),
 () => exec('npm run test')
]); 

只需安装npm

npm install npm

然后在你的程序中:

npm.commands.run('dev', (err) => { ... });

有关更多信息,请参阅来源。 npm.command对象是 npm 的非官方 API。 请注意,使用execspawn执行npm更安全,因为该 API 是非官方的。

使用PM2 ,它真的有用且简单...

npm install pm2
const pm2 = require('pm2');

pm2.start({
    script: 'npm -- run monitorTheWeather',
    autorestart : false 
  }, (err, apps) => {
    pm2.disconnect()
    if (err) { throw err }
  })

这是一个可以在所有平台上可靠运行的解决方案。 它也非常简洁。 将其放入build.js ,然后运行node build

const {execSync} = require('child_process')

execSync("npm run clean")
execSync("npm run minify")
execSync("npm run build_assets")

它会在 npm 异常终止时立即中止。

在打字稿中:

import { exec } from 'child_process'
import { promisify } from 'util'

const asyncExec = promisify(exec)
;(async () => {
   await asyncExec('npm run db:seed')
   await asyncExec('npm start')
})()

npm 文档建议使用shelljs<\/code> :

var shell = require("shelljs");

shell.exec("echo shell.exec works");
shell.exec("npm run dev");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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