简体   繁体   English

使用 npm 在多个节点项目目录中运行脚本

[英]Running scripts inside multiple node project directories with npm

The Context上下文

I have one main project which has multiple node projects inside that as subdirectories.我有一个主项目,其中有多个节点项目作为子目录。 each one with their own node_modules directories and package.json files.每个都有自己的node_modules目录和package.json文件。 I want to have an npm script defined in my main package.json files which runs npm scripts from each of those projects concurrently.我想在我的主要package.json文件中定义一个 npm 脚本,它同时运行来自每个项目的 npm 脚本。

The Code编码

My directory structure is like this:我的目录结构是这样的:

main:
  ...
  package.json

  - sub-project-1
    - ...
      package.json
  - sub-project-2
    ...
    package.json

Sub-project-1/package.json:子项目 1/package.json:

...
"scripts": {
  "start": "node run foo.js"
}

Sub-project-2/package.json:子项目 2/package.json:

...
"scripts": {
  "start": "node run bar.js"
}

Main package.json:主包.json:

...
"scripts": {
  "start": "/* Here I want to do something like npm sub-project-1/ start && npm sub-project-2/ start */
}

Now, obviously I could copy and paste the commands in sub-project-1/package.json 's start script and sub-project-2/package.json 's start script into a bash script and run that instead.现在,显然我可以将sub-project-1/package.jsonstart脚本和sub-project-2/package.json的启动脚本中的命令复制并粘贴到 bash 脚本中,然后运行它。 But I want to be able to change those npm start scripts without having to manually change the bash script every time.但是我希望能够更改那些npm start脚本,而不必每次都手动更改 bash 脚本。 Is there a way to do this?有没有办法做到这一点?

1.You can also write a python script that parses all the package.jsons of the subdirectories and then generate the master package.json file 1.也可以写一个python脚本,解析所有子目录的package.jsons,然后生成master package.json文件

2.or You can also write a python script that parses all the package.jsons of the subdirectories and then generate a shellscript where the mater package.json will call it in the "start". 2.或者你也可以写一个python脚本来解析所有子目录的package.jsons,然后生成一个shellscript,其中mater package.json会在“start”中调用它。

The following is not concurrent;以下不是并发的; however, you can change the npm start scripts with this approach.但是,您可以使用这种方法更改 npm start 脚本。

I should mention also that it's not the world's most scalable approach.我还应该提到它不是世界上最具可扩展性的方法。 But it's simple, so I thought it might be helpful to share.但这很简单,所以我认为分享可能会有所帮助。

Here goes ...开始 ...

Main package.json:主包.json:

...
"scripts": {
  "start": "cd Sub-project-1 && npm run start && cd ../Sub-project-2 && npm run start && cd ../ && <parent project start script here>"
}

With this script, you're just meandering through the sub projects and then coming back up to run the parent project's script.使用此脚本,您只需在子项目中蜿蜒曲折,然后再回来运行父项目的脚本。

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

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