在“react-scripts start”之后顺序执行NPM脚本

4

使用React开发Electron应用程序。目前,为了启动项目,我需要运行典型的npm start命令,该命令将运行react-scripts start脚本。

这会启动开发服务器。一旦开发服务器启动,我会打开第二个终端窗口,并运行一个脚本来启动Electron:npm run start-electron,它会在Electron窗口中打开我的React应用程序。

虽然这种方式可以正常工作,但我想知道是否有一种方法可以创建一个脚本,实现以下功能:

  • 启动开发服务器
  • 等待开发服务器启动完成
  • 然后启动Electron

我尝试在package.json中设置一个顺序脚本,但它只会启动开发服务器。例如:npm run start && npm run start-electron

这不是必须的。两个终端选项也能正常工作,只是不知道是否有更好的方法。

5个回答

3

是的,这是可能的。我在我的项目中使用 concurrently 来实现它。

npm i concurrently

然后添加一个新的脚本,比如叫做 dev,在你的脚本中:

"dev": "concurrently \"npm run start\" \"npm run start-electron\""

现在只需要运行 npm run dev 即可。


快接近了!看起来这两个同时运行了,因为我立刻得到了一个电子窗口,但是开发服务器还没有启动,所以它是一个空白屏幕。一旦开发服务器启动,我就可以刷新,这不是什么大问题。话虽如此,有可能强制第二个脚本等待第一个脚本完成吗? - Andrew
我会选择刷新/执行您需要执行的操作,但如果您真的想要,可以通过将concurrently与wait-on结合使用来实现它,请参阅此处:https://dev59.com/ZFYN5IYBdhLWcg3w9Mbr#48192578 - Slim
1
是的。刚刚尝试了并发和等待,现在我不需要刷新了。电子脚本直到我的本地开发服务器启动后才运行。 - Andrew

2

我有完全相同的情况,下面的脚本对我有效(记得安装 wait-on

  "scripts": {
    "start-reactjs": "PORT=25610 react-scripts start",
    "start-electron": "wait-on http://localhost:25610 && electron .",
    "start": "npm run start-electron & npm run start-reactjs"
  }

我需要结合使用concurrentlywait-on才能在服务器启动后立即成功运行一个脚本。 - Mutu A.

0

我通过使用concurrently解决了这个问题。

npm i concurrently

In my package.json

"build": "concurrently \"npm run build-react\" && npm run build-jsx",

我正在使用它来构建一个使用React的Adobe扩展程序,并且我需要在react-scripts build之后打包我的extendscript,否则会删除我的.jsxbin文件。


0
你可以尝试使用 start-server-and-test npm 模块。它有不同的目的,但对于你的情况可能有效。
从文档中得知:

This command is meant to be used with NPM script commands. If you have a "start server", and "test" script names for example, you can start the server, wait for a url to respond, then run tests. When the test process exits, the server is shut down.

    "scripts": {
        "start-server": "npm start",
        "test": "mocha e2e-spec.js",
        "ci": "start-server-and-test start-server http://localhost:8080 test"
        } 
    } 

To execute all tests simply run npm run ci.

另一个选择可能是像@Slim所说的那样,将concurrentlywait-on结合起来使用

从文档中可以看到:

wait-on会在文件停止增长一段时间后等待触发可用性,这对于监视正在构建的文件非常有用。同样,wait-on会在其他资源保持可用状态一段时间后等待触发成功。


0

你可以在根目录下创建一个扩展名为.sh的脚本,它可以包含所有需要执行的操作。

  npm start
  npm run start-electron

第二种方法是在package.json中创建自定义脚本。

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "customStart":"npm run start && npm run start-electron"
  },

运行此脚本

npm run customStart

不幸的是,我尝试了顺序运行技术,但它们只执行了前半部分。可能与"react-scripts start"有关吧。 - Andrew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接