前端工程化实现并发执行的解决方案

做工程化前端开发过程中,我们经常会遇到需要同时执行多个命令的情况。例如,我们可能需要同时运行多个监听程序,以便在文件发生更改时自动编译和更新输出。

那么如何进行多个前端任务的并发执行呢?

下面有几种方法可以实现:

语法如下:

使用连接符

命令连接符有&&&|||四种类型,意义如下:

符号 说明
&& 顺序执行多条命令,当碰到执行出错的命令后将不执行后面的命令
& 并行执行多条命令
|| 顺序执行多条命令,当碰到执行正确的命令后将不执行后面的命令
| 管道符

例如,我们定义了两个脚本文件,分别是app.jsapp2.js,在两个脚本文件中分别定义两个定时器,延时输出一段文字。

app.js

1
2
3
setTimeout(() => {
console.log('app.js')
}, 2000)

app2.js

1
2
3
setTimeout(() => {
console.log('app2.js')
}, 1000)

然后在package.json中定义脚本命令如下:

1
2
3
"scripts": {
"test": "node app.js && node app2.js",
}

那么我们执行npm run test命令,将会顺序执行两个脚本文件,输出结果如下:

1
2
3
4
5
6
7
$ npm run test

> webpacktest@1.0.0 test
> node app && node app2

app.js
app2.js

我们将命令改成node app.js & node app2.js,将会并行执行两个脚本文件,输出结果如下:

1
2
3
"scripts": {
"test": "node app.js & node app2.js",
}

那么我们再执行npm run test命令时,输出结果变成如下:

1
2
3
4
5
6
7
$ npm run test

> webpacktest@1.0.0 test
> node app && node app2

app2.js
app.js

可以看到,两个脚本文件的输出顺序发生了变化,这是因为&符号会在后台异步运行node app2.js命令,所以node app2.js命令会先执行。

使用npm-run-all

使用 npm-run-all 模块,也可以同时运行多个npm脚本。

首先,我们需要安装 npm-run-all 模块:

1
npm install npm-run-all

然后在 package.json 中:

1
2
3
4
5
"scripts": {
"app:1": "node app",
"app:2": "node app2",
"test": "npm-run-all --parallel app:*"
}

运行 npm run test 即可同时执行 app:1 和 app:2,输出结果为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ npm run test

> webpacktest@1.0.0 test
> node app & node app2

app.js
app2.js

> webpacktest@1.0.0 test
> npm-run-all --parallel app:*


> webpacktest@1.0.0 app:2
> node app2


> webpacktest@1.0.0 app:1
> node app

app2.js
app.js

使用 concurrently

concurrentlynpm-run-all类似,也是解决前端工程化开发时,处理多任务并行的解决方案之一。

安装

1
npm install concurrently

concurrently的基础配置格式如下:

1
2
3
4
5
"scripts": {
"app:1": "node app",
"app:2": "node app2",
"test": "concurrently \"npm run app:1\" \"npm run app:2\" "
}

这里要注意,concurrently命令中的命令需要用双引号包裹,并且转义,切不可使用单引号,否则会报错。

运行npm run test,输出结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ npm run test

> webpacktest@1.0.0 test
> concurrently "npm run app:1" "npm run app:2"

[0]
[0] > webpacktest@1.0.0 app:1
[0] > node app
[0]
[1]
[1] > webpacktest@1.0.0 app:2
[1] > node app2
[1]
[1] app2.js
[1] npm run app:2 exited with code 0
[0] app.js
[0] npm run app:1 exited with code 0

关于concurrently的更多用法,可以参考我的另一边文章前端工程化多任务并发利器-concurrently

本文永久链接: https://www.mulianju.com/run-multi-fe-projects/