如何在一个项目中融合Cocos和React

Cocos作为一个游戏引擎,在开发UI方面是有短板的,不仅是性能上的短板,比如Cocos中的图片体积一般都比较大,而React则可以使用Webp这种格式,同时在开发效率上,Cocos的UI开发效率是远不如React的,社区里也经常会遇到大家融合这两种技术栈,不过一般都是简单的放到一起,各自开发,然后最后联调,这篇文章就是为了提供一种思路,可以让两者在开发的时候就在同一个页面,并且任何改动都可以实时生效。

可行性分析

首先我们要明白这两种技术栈能融合在一起的原理,也就是他们两个必须在某个层次能够打通

我们可以看一下React项目的结构,首先是一个入口文件,即index.html,

1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Interaction React</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

其次是入口文件中唯一引入的tsx脚本文件

1
2
3
4
5
6
7
8
9
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'

createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

从这两个文件,结合React的原理,我们明白,其实模版中只需要一个根节点,然后脚本中通过js的执行,在根节点上动态创建就可以实现整个页面了

那么理论上我们把两个文件的引入放到cocos web的入口文件中即可做到将这两个技术栈融合。

我们如果在本地启动了Cocos,点击在浏览器中运行,打开开发者工具,就可以看到Cocos Web的入口文件大致如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Interaction React</title>
<link rel="stylesheet" href="./cocos-index.css">
</head>
<body>
<div class="toolbar hide" style="display: none;">
<div class="item">
<div
id="view-select"
class="view-select-container"
value="Default"
tabindex="-1"
>
<div class="view-select">
<div class="label">
<span id="name">设计分辨率 (375X812)</span>
</div>
<i class="arrow-triangle"></i>
</div>
<div class="options">
<ul>
<li class="selected" data-device="Default">
设计分辨率 (375X812)
</li>

<li class="" data-device="FullScreen">全屏</li>

<li class="" data-device="WebpageFullScreen">网页全屏</li>

<li class="separator"></li>

<li class="" data-device="iPhone SE">iPhone SE (375X667)</li>

<li class="" data-device="iPhone XS Max">
iPhone XS Max (414X896)
</li>

<li class="" data-device="iPhone XS">iPhone XS (375X812)</li>

<li class="" data-device="iPhone XR">iPhone XR (414X896)</li>

<li class="" data-device="iPhone 8 Plus">
iPhone 8 Plus (414X736)
</li>

<li class="" data-device="iPhone 8">iPhone 8 (375X667)</li>

<li class="" data-device="Galaxy S9 Plus">
Galaxy S9 Plus (412X846)
</li>

<li class="" data-device="Galaxy S9">Galaxy S9 (360X740)</li>

<li class="" data-device="Galaxy S7">Galaxy S7 (360X640)</li>

<li class="" data-device="Huawei P20 Lite">
Huawei P20 Lite (360X760)
</li>

<li class="" data-device="Huawei P20 Pro">
Huawei P20 Pro (360X747)
</li>

<li class="" data-device="Huawei P20">Huawei P20 (360X748)</li>

<li class="" data-device="Huawei P10">Huawei P10 (360X640)</li>

<li class="" data-device="Moto Z2">Moto Z2 (360X640)</li>

<li class="" data-device="Redmi Note 5">
Redmi Note 5 (393X786)
</li>

<li class="" data-device="Redmi Note 4">
Redmi Note 4 (360X640)
</li>

<li class="" data-device="Pixel 3 XL">Pixel 3 XL (393X786)</li>

<li class="" data-device="Pixel 2 XL">Pixel 2 XL (412X823)</li>

<li class="" data-device="Pixel 2">Pixel 2 (412X640)</li>

<li class="" data-device="Nexus 6P">Nexus 6P (412X732)</li>

<li class="" data-device="Nexus 6">Nexus 6 (360X640)</li>

<li class="" data-device="LG K20">LG K20 (360X640)</li>

<li class="" data-device="LG K7">LG K7 (320X570)</li>

<li class="" data-device="ZTE ZMAX Pro">
ZTE ZMAX Pro (360X640)
</li>

<li class="" data-device="ZTE Majesty Pro">
ZTE Majesty Pro (320X570)
</li>
</ul>
</div>
</div>
</div>
<div class="item"><button id="btn-rotate" class="">Rotate</button></div>
<span style="font-size: small" class="item">Debug Mode:</span>
<div class="item">
<select id="opts-debug-mode" value="VERBOSE">
<option value="NONE">None</option>
<option value="VERBOSE">Verbose</option>
<option value="INFO">Info</option>
<option value="WARN">Warn</option>
<option value="ERROR">Error</option>
<option value="INFO_FOR_WEB_PAGE">Info For Web Page</option>
<option value="WARN_FOR_WEB_PAGE">Warn For Web Page</option>
<option value="ERROR_FOR_WEB_PAGE">Error For Web Page</option>
</select>
</div>
<div class="item">
<button id="btn-show-fps" class="checked">Show FPS</button>
</div>
<div class="item">
<span style="font-size: small" class="item">FPS:</span
><input id="input-set-fps" type="number" value="60" />
</div>
<div style="margin-right: 0" class="item">
<button id="btn-pause">Pause</button><button id="btn-step">Step</button>
</div>
<div class="item">
<button id="btn-step" style="display: none">Step</button>
</div>
<div id="step-length">
<span>Step Length: </span>
<input type="text" value="1" />
<span>ms</span>
</div>
</div>

<div id="content" class="content" style="overflow: hidden">
<div class="contentWrap">
<div
id="GameDiv"
class="wrapper"
style="
display: flex;
justify-content: center;
align-items: center;
transform: rotate(0deg);
margin: 0px auto;
width: 359px;
height: 847px;
"
>
<div id="Cocos3dGameContainer" style="width: 100%; height: 100%">
<canvas
id="GameCanvas"
tabindex="-1"
style="background-color: ''"
width="718"
height="1694"
></canvas>
</div>
<div
id="splash"
class="portrait"
style="visibility: visible; display: none"
>
<div class="progress-bar stripes">
<span style="width: 60%"></span>
</div>
</div>
<div id="bulletin">
<div id="sceneIsEmpty" class="inner">
预览场景中啥都没有,加点什么,或在编辑器中打开其它场景吧
</div>
</div>
<div class="error" id="error">
<div class="title">
Error <i>(Please open the console to see detailed errors)</i>
</div>
<div class="error-main"></div>
<div class="error-stack"></div>
</div>
</div>
</div>
</div>
<!-- v-console Support.(Optional) -->

<script src="/node_modules/vconsole/dist/vconsole.min.js"></script>
<script>
window.VConsole && (window.vConsole = new VConsole());
</script>

<!-- Polyfills bundle. -->
<script src="/scripting/polyfills/bundle.js"></script>

<!-- Import map that map the engine feature unit modules. -->
<script
src="/scripting/engine/bin/.cache/dev/preview/import-map.json"
type="systemjs-importmap"
></script>

<!-- Import map that map the entry of project module(s). -->
<script
src="/scripting/x/import-map.json"
type="systemjs-importmap"
></script>

<!-- Import map that map 'cc', 'cc/env'. -->
<script
src="/scripting/import-map-global"
type="systemjs-importmap"
></script>

<!-- SystemJS support. -->
<script src="/scripting/systemjs/system.js"></script>

<!-- Setup the detailed resolution. -->
<script>
System.setResolutionDetailMapCallback(function () {
var url = new URL(
"/scripting/x/resolution-detail-map.json",
window.location
);
return fetch(url)
.then(function (response) {
return response.json();
})
.then(function (json) {
return { json, url: url.href };
});
});
</script>

<script src="/scripting/engine/bin/.cache/dev/preview/bundled/index.js"></script>

<!-- Manifest file. -->
<script name="setting" src="/settings.js?scene=current_scene"></script>

<script>
window.onload = function () {
System.import("/preview-app/index.js")
.then(function (mod) {
return mod.bootstrap({
engineBaseUrl: "/scripting/engine",
settings: window._CCSettings,
devices: {
Default: {
name: "设计分辨率",
width: 375,
height: 812,
ratio: 1,
},
FullScreen: { name: "全屏" },
WebpageFullScreen: { name: "网页全屏" },
__separator__: { name: "__separator__" },
"iPhone SE": {
name: "iPhone SE",
width: 375,
height: 667,
ratio: 2,
},
"iPhone XS Max": {
name: "iPhone XS Max",
width: 414,
height: 896,
ratio: 3,
},
"iPhone XS": {
name: "iPhone XS",
width: 375,
height: 812,
ratio: 3,
},
"iPhone XR": {
name: "iPhone XR",
width: 414,
height: 896,
ratio: 2,
},
"iPhone 8 Plus": {
name: "iPhone 8 Plus",
width: 414,
height: 736,
ratio: 2.6,
},
"iPhone 8": {
name: "iPhone 8",
width: 375,
height: 667,
ratio: 2,
},
"Galaxy S9 Plus": {
name: "Galaxy S9 Plus",
width: 412,
height: 846,
ratio: 3.5,
},
"Galaxy S9": {
name: "Galaxy S9",
width: 360,
height: 740,
ratio: 4,
},
"Galaxy S7": {
name: "Galaxy S7",
width: 360,
height: 640,
ratio: 4,
},
"Huawei P20 Lite": {
name: "Huawei P20 Lite",
width: 360,
height: 760,
ratio: 3,
},
"Huawei P20 Pro": {
name: "Huawei P20 Pro",
width: 360,
height: 747,
ratio: 3,
},
"Huawei P20": {
name: "Huawei P20",
width: 360,
height: 748,
ratio: 3,
},
"Huawei P10": {
name: "Huawei P10",
width: 360,
height: 640,
ratio: 3,
},
"Moto Z2": {
name: "Moto Z2",
width: 360,
height: 640,
ratio: 4,
},
"Redmi Note 5": {
name: "Redmi Note 5",
width: 393,
height: 786,
ratio: 2.75,
},
"Redmi Note 4": {
name: "Redmi Note 4",
width: 360,
height: 640,
ratio: 3,
},
"Pixel 3 XL": {
name: "Pixel 3 XL",
width: 393,
height: 786,
ratio: 3.67,
},
"Pixel 2 XL": {
name: "Pixel 2 XL",
width: 412,
height: 823,
ratio: 3.5,
},
"Pixel 2": {
name: "Pixel 2",
width: 412,
height: 640,
ratio: 2.6,
},
"Nexus 6P": {
name: "Nexus 6P",
width: 412,
height: 732,
ratio: 3.5,
},
"Nexus 6": {
name: "Nexus 6",
width: 360,
height: 640,
ratio: 4,
},
"LG K20": { name: "LG K20", width: 360, height: 640, ratio: 2 },
"LG K7": { name: "LG K7", width: 320, height: 570, ratio: 1.5 },
"ZTE ZMAX Pro": {
name: "ZTE ZMAX Pro",
width: 360,
height: 640,
ratio: 3,
},
"ZTE Majesty Pro": {
name: "ZTE Majesty Pro",
width: 320,
height: 570,
ratio: 1.5,
},
},
});
})
.catch(function (err) {
console.error(err);
});
};
</script>

<script
type="text/javascript"
src="chrome-extension://dlkffcaaoccbofklocbjcmppahjjboce/inject/index.js"
></script>
</body>
</html>

我们只需要将React的节点加入即可将两个技术栈融合,融合后的文件如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Interaction React</title>
<link rel="stylesheet" href="./cocos-index.css">
</head>
<body>
<!-- React相关内容 start -->
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
<!-- React相关内容 end -->
<div class="toolbar hide" style="display: none;">
...
</div>

<div id="content" class="content" style="overflow: hidden">
...
</div>
<!-- v-console Support.(Optional) -->

<script src="/node_modules/vconsole/dist/vconsole.min.js"></script>
<script>
window.VConsole && (window.vConsole = new VConsole());
</script>

<!-- Polyfills bundle. -->
<script src="/scripting/polyfills/bundle.js"></script>

<!-- Import map that map the engine feature unit modules. -->
<script
src="/scripting/engine/bin/.cache/dev/preview/import-map.json"
type="systemjs-importmap"
></script>

<!-- Import map that map the entry of project module(s). -->
<script
src="/scripting/x/import-map.json"
type="systemjs-importmap"
></script>

<!-- Import map that map 'cc', 'cc/env'. -->
<script
src="/scripting/import-map-global"
type="systemjs-importmap"
></script>

<!-- SystemJS support. -->
<script src="/scripting/systemjs/system.js"></script>

<!-- Setup the detailed resolution. -->
<script>
System.setResolutionDetailMapCallback(function () {
...
});
</script>

<script src="/scripting/engine/bin/.cache/dev/preview/bundled/index.js"></script>

<!-- Manifest file. -->
<script name="setting" src="/settings.js?scene=current_scene"></script>

<script>
...
</script>

<script
type="text/javascript"
src="chrome-extension://dlkffcaaoccbofklocbjcmppahjjboce/inject/index.js"
></script>
</body>
</html>

具体方案

上面的可行性分析,让我们明白,将两种技术栈融合是具有理论上的可行性的,那么接下来我们只需要将这种可行性付诸实践,并提供一个尽量好的体验即可

工具准备

  1. 打包工具:我们选择最新的Vite,一方面是更快,另一方面我们很多需要的能力Vite本体即可提供,不需要安装插件
  2. React版本:我们选择React18版本,其他版本应该问题也不大
  3. Cocos版本:我们选择3.8.1版本

开发环境搭建

  1. 通过vite创建react-ts项目
1
npm create vite my-interaction-react-app --template react-ts
  1. my-interaction-react-app根目录下创建game目录,并使用Cocos引擎在该目录下创建项目

  2. 替换my-interaction-react-app根目录下的index.html为原理中我们提到的融合的入口文件

  3. 此时如果我们运行项目,会发现,很多请求都404了,因为入口文件中请求cocos资源的请求都发给了vite服务器而非cocos的服务器,我们只需要挨个把这些请求从vite代理到cocos的本地服务器即可,具体过程不赘述,这里提供一个最基本的配置,如果有更多的资源可以自己再替换

有一点要注意的是,cocos也有自己的入口css文件,最好在模版中重命名为cocos-index.css,被vite代理后,rewrite为index.css,避免和react的自身的样式文件冲突,其次socket相关的请求要标注ws为true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vite.dev/config/
const cocosDevServer = "http://localhost:7456";
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
"/socket.io": {
target: cocosDevServer,
changeOrigin: true,
ws: true,
},
"/scripting": {
target: cocosDevServer,
changeOrigin: true,
},
"/settings": {
target: cocosDevServer,
changeOrigin: true,
},
"/preview-app": {
target: cocosDevServer,
changeOrigin: true,
},
"/node_modules/vconsole": {
target: cocosDevServer,
changeOrigin: true,
},
"/assets/main": {
target: cocosDevServer,
changeOrigin: true,
},
"/assets/internal": {
target: cocosDevServer,
changeOrigin: true,
},
"/assets/general": {
target: cocosDevServer,
changeOrigin: true,
},
"/cocos-index.css": {
target: cocosDevServer,
changeOrigin: true,
rewrite: (path: string) => path.replace('/cocos-index.css', '/index.css')
},
"/scene": {
target: cocosDevServer,
changeOrigin: true,
},
"/engine_external": {
target: cocosDevServer,
changeOrigin: true,
},
"/query-extname": {
target: cocosDevServer,
changeOrigin: true,
},
},
},
build: {
emptyOutDir: false,
},
css: {
modules: {
localsConvention: "camelCaseOnly",
},
preprocessorOptions: {
less: {
javascriptEnabled: true,
},
},
},
});

经过这些步骤,你就可以得到和vite开发一样的丝滑体验,即使你是在cocos引擎中拖拽了某个Node的位置,回到浏览器会发现Cocos更新了,虽然没有完全复用Vite的局部更新

构建环境搭建

上述的步骤只是保证了开发环境的丝滑体验,但是我们如何在打包的时候将二者打包到一起,我们有两个问题要解决:

  1. 如何自定义打包模版,因为刚才我们是改了react项目的入口文件,我们cocos的打包每次的产物最好都是有hash的,所以我们每次都需要用cocos打包产物中的index.html去替换react根目录下的index.html
  2. 如何将打包产物移动到react产物目录下

关于第一个问题,我们可以在cocos目录下,也就是game目录下创建build-template目录,在该目录下,如果我们是打包成手机版,我们可以创建web-mobile目录,在其中创建index.ejs,内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<html>
<head>
<meta charset="utf-8"></meta>

<title><%= projectName %></title>


<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1,minimum-scale=1,maximum-scale=1,minimal-ui=true"></meta>


<meta name="apple-mobile-web-app-capable" content="yes"></meta>
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"></meta>
<meta name="format-detection" content="telephone=no"></meta>


<meta name="renderer" content="webkit"></meta>
<meta name="force-rendering" content="webkit"></meta>

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"></meta>
<meta name="msapplication-tap-highlight" content="no"></meta>


<meta name="full-screen" content="yes"></meta>
<meta name="x5-fullscreen" content="true"></meta>
<meta name="360-fullscreen" content="true"></meta>



<meta name="x5-page-mode" content="app"></meta>




<link rel="stylesheet" type="text/css" href="<%= cssUrl %>">

</head>
<body>
<div id="root"></div>
<script data-for="react" type="module" src="/src/main.tsx"></script>
<div id="GameDiv" cc_exact_fit_screen="true">
<div id="Cocos3dGameContainer">
<canvas id="GameCanvas" oncontextmenu="event.preventDefault()" tabindex="99"></canvas>
</div>
</div>

<script>
window.overrideCocos = {
server: 'window.overrideCocos.server',
settingsPath: 'window.overrideCocos.settingsPath'
}
</script>

<%- include(cocosTemplate, {}) %>

</body>
</html>

这段模版中融合了react和cocos,同时没有开发环境下需要的哪些特殊的debug代码的入口

另外需要注意的是,我在这里注入了一段脚本,在window上挂在了几个变量,我这里是为了在cocos启动后的application.js中替换一些参数,具体方法是在web-mobile下创建application.ejs,如下:

之所以这样所,是因为,有可能找不到settings的文件,所以需要特意指定下,如果你们有报这个错,可以忽略这一步,如果你遇到了其他启动参数的错误,可以用我这个方法解决

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
let cc;
export class Application {
constructor () {
this.showFPS = false; // 是否打开 profiler, 通常由编辑器构建时传入,你也可以指定你需要的值
}

init (engine) {
cc = engine;
cc.game.onPostBaseInitDelegate.add(this.onPostInitBase.bind(this)); // 监听引擎启动流程事件 onPostBaseInitDelegate
cc.game.onPostSubsystemInitDelegate.add(this.onPostSystemInit.bind(this)); // 监听引擎启动流程事件 onPostSubsystemInitDelegate
}

onPostInitBase () {
// 实现一些自定义的逻辑
}

onPostSystemInit () {
// 实现一些自定义的逻辑
}

start () {
return cc.game.init({ // 以需要的参数运行引擎
debugMode: <%= debugMode %> ? cc.DebugMode.INFO : cc.DebugMode.ERROR,
settingsPath: window.overrideCocos.settingsPath, // 传入 settings.json 路径
overrideSettings: { // 对配置文件中的部分数据进行覆盖,第二部分会详细介绍这个字段
// assets: {
// preloadBundles: [{ bundle: 'main', version: 'xxx' }],
// }
assets: {
server: window.overrideCocos.server
},
assetOptions: {
server: window.overrideCocos.server
},
profiling: {
showFPS: this.showFPS,
}
}
}).then(() => cc.game.run());
}
}

对于如何将cocos产物移动到react产物目录下,其实有很多方法,我这里采用的是开发了一个cocos的plugin,在afterbuild的hook中复制并且动态修改我在index.ejs中挂载到window上的变量的实际的值,有点类似vite打包时替换环境变量的操作

以上只是基本原理,具体遇到什么问题可以自己解决