egret-sdk-wx小游戏

命令

1
2
3
4
# debug
egret run --target wxgame
# release
egret publish --target wxgame

资源加载

外网资源

复制一份资源目录,把需要丢到包里面的资源移除出来,然后重新生成default.res.json的内容,目录结构要保持白鹭一致。然后修改main.ts里面加载res.json的地方。在然后把外网资源发布到外网web服务器。

1
2
3
4
5
6
// 原来
RES.loadConfig("resource/default.res.json", "resource/");

// 在加载原来的资源加载后面新加一句加载外网配置的代码
RES.loadConfig("resource/default.res.json", "resource/");
RES.loadConfig("http://173.248.241.51/resource/default.res.json", "http://173.248.241.51/resource/");

包资源加载

复制一份资源目录,把需要外网加载的资源移除出来,然后重新生成default.res.json的内容,目录结构要保持白鹭一致。不需要做任何的代码修改

资源跨域处理

main.tscreateChildren开头加上代码

1
2
// 图片资源跨域
egret.ImageLoader.crossOrigin = "anonymous";

第三方库丢失

gameThirdScriptError
xxxxx is not defined
ReferenceError: xxxxx is not defined

解决的方法,

  • 将js库手写一个ts库
  • 引入js库时,将库丢到window里面,例如我有一个库xxxxx,需要在js库代码最后面添加window.xxxxx = xxxxx

  • 音效不能连续播放,同一个音效同一时间只能播放一个
  • 音效播放间隔不能太短,建议弄个0.2秒左右的间隔
  • 未播放过的音效,获取的时候音效长度都是0

https://blog.csdn.net/qq_23375733/article/details/81229223
https://blog.csdn.net/qq_30117429/article/details/79164833

分包加载

创建subpackage.ts

在项目的scripts/wxgame目录里面创建subpackage.ts

subpackage.ts代码
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
import * as path from 'path';

const manifest = {
initial: [],
game: []
}

type SubPackagePluginOptions = {

output: string,

subPackages: {
root: string,
includes: string[]
}[],

verbose?: boolean
}

export class SubPackagePlugin {

private verboseInfo: { filename: string, new_file_path: string }[] = [];

constructor(private options: SubPackagePluginOptions) {

}

async onFile(file: plugins.File) {
const filename = file.relative;
console.log(filename);
const extname = path.extname(filename);
if (extname == ".js") {
const basename = path.basename(filename);
let new_file_path = "js/" + basename.substr(0, basename.length - file.extname.length) + file.extname;

let isSubPackage = false;
if (this.options.subPackages) {
this.options.subPackages.forEach(function (item) {
if (item.includes) {
item.includes.forEach(function (item2) {
if (item2 == filename) {
new_file_path = item.root + "/" + basename.substr(0, basename.length - file.extname.length) + file.extname;
isSubPackage = true;
}
});
}
});
}
if (this.options.verbose) {
console.log(`SubPackagePlugin: ${filename} isSubPackage: ${isSubPackage}`);
}

file.path = path.join(file.base, new_file_path);

if (!isSubPackage) {
const relative = file.relative.split("\\").join('/');
if (file.origin.indexOf('libs/') >= 0) {
manifest.initial.push(relative);
}
else {
manifest.game.push(relative);
}
}

if (this.options.verbose) {
this.verboseInfo.push({ filename, new_file_path })
}
}
return file;
}
async onFinish(pluginContext: plugins.CommandContext) {
const output = this.options.output;
const extname = path.extname(output);
let contents = '';
switch (extname) {
case ".json":
contents = JSON.stringify(manifest, null, '\t');
break;
case ".js":
contents = manifest.initial.concat(manifest.game).map((fileName) => `require("${fileName}")`).join("\n")
break;
}
pluginContext.createFile(this.options.output, new Buffer(contents));
if (this.options.subPackages) {
const self = this;
this.options.subPackages.forEach(function (item) {
let gameJS = "";
// 配置的文件必须存在
gameJS = item.includes.map((file) => `require("${path.basename(file)}")`).join("\n");
pluginContext.createFile(path.join(item.root, "game.js"), new Buffer(gameJS));
});
}
if (this.options.verbose) {
this.verboseInfo.forEach((item) => {
console.log(`SubPackagePlugin: ${item.filename} => ${item.new_file_path}`);
});
}
}
}

修改config.wxgame.ts

  • 将 ManifestPlugin 替换为 SubPackagePlugin (build 和 publish)
  • 修改 config.wxgame.ts 中的 CleanPlugin,将 subpackage 对应的目录清除
config.wxgame.ts参考
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
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>

import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, CleanPlugin } from 'built-in';
import { WxgamePlugin } from './wxgame/wxgame';
import { SubPackagePlugin } from './wxgame/subpackage';
import { CustomPlugin } from './myplugin';
import * as defaultConfig from './config';

const config: ResourceManagerConfig = {

buildConfig: (params) => {

const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_wxgame`;
if (command == 'build') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource", "subPack1"] }),
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new WxgamePlugin(),
new SubPackagePlugin({
output: 'manifest.js',
subPackages: [
{
root: "subPack1",
"includes": [
"main.js"
]
}
]
})
]
}
}
else if (command == 'publish') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource", "subPack1"] }),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new WxgamePlugin(),
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}
]),
new SubPackagePlugin({
output: 'manifest.js',
subPackages: [
{
root: "subPack1",
"includes": [
"main.min.js"
]
}
]
})
]
}
}
else {
throw `unknown command : ${params.command}`;
}
},

mergeSelector: defaultConfig.mergeSelector,

typeSelector: defaultConfig.typeSelector
}



export = config;

创建EgretSubpackageLoading.js

发布微信后,在微信的主目录里面,即egret.wxgame.js的目录,创建EgretSubpackageLoading.js

EgretSubpackageLoading.js代码
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
class EgretSubPackageLoading extends egret.DisplayObjectContainer {
constructor() {
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
EgretSubPackageLoading.instance = this;
}

onAddToStage() {
// this.txt = new egret.TextField();
// this.txt.textAlign = egret.HorizontalAlign.CENTER;
// this.txt.width = this.stage.stageWidth;
// this.txt.y = this.stage.stageHeight - this.txt.size >> 1;
// this.txt.textColor = 0xff0000;
// this.addChild(this.txt);
}

setProgress(res) {
// iOS真机为totalBytesWriten 微信官方将于近期修复 2018.6.19
// this.txt.text = `${res.totalBytesWritten || res.totalBytesWriten} / ${res.totalBytesExpectedToWrite}`;
console.log(res.progress);
}

onSuccess() {
const stage = this.stage;
stage.removeChild(this);
EgretSubPackageLoading.instance = null;
// 创建文档类,开发者需要根据自身项目更改
const main = new Main();
stage.addChild(main);
}
}

window.EgretSubPackageLoading = EgretSubPackageLoading;

修改game.json

修改微信小游戏项目的 game.json,引入 subpackages 属性实现分包加载

game.json参考
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"deviceOrientation": "portrait",
"networkTimeout": {
"request": 5000,
"connectSocket": 5000,
"uploadFile": 5000,
"downloadFile": 5000
},
"openDataContext": "openDataContext",
"subpackages": [
{
"name": "subPack1",
"root": "subPack1"
}
]
}

修改game.js

修改微信小游戏项目的 game.js,添加调用 wx.loadSubPackage 的逻辑

game.js代码参考
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
require('./weapp-adapter.js');
require('./platform.js');
require('./manifest.js');
require('./egret.wxgame.js');

let runOptions = {
//以下为自动修改,请勿修改
//The following is automatically modified, please do not modify
//----auto option start----
entryClassName: "Main",
orientation: "auto",
frameRate: 30,
scaleMode: "fixedWidth",
contentWidth: 900,
contentHeight: 1600,
showFPS: false,
fpsStyles: "x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9",
showLog: false,
maxTouches: 2,
//----auto option end----
audioType: 0,
calculateCanvasScaleFactor: function (context) {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
}
};

const runEgret = function () {
egret.runEgret(runOptions);
}

if (wx.loadSubpackage) {
require("./EgretSubPackageLoading.js");
runOptions.entryClassName = "EgretSubPackageLoading";
runEgret();
let task = wx.loadSubpackage({
// 开发者根据自身需求更改
name: "subPack1",
success: function () {
EgretSubPackageLoading.instance.onSuccess();
}
});

task.onProgressUpdate(res => {
EgretSubPackageLoading.instance.setProgress(res);
})
}
else {
//
require("./subPack1/game.js");
runEgret();
}