Electron / Node / TS / Vue 的几个坑
做 UpgradeE 时记下的一些踩坑。
发布 2017年4月20日 标签
#javascript
#electron
#node
~/posts/electron-pit $ cat post.md
Electron 的坑
- 用
remote调用主进程的全局变量时,不能传自定义对象。硬传的话,prototype上的方法全丢,私有变量的边界也保不住。 - 调整
icon不能用NativeImage,也不能直接传路径,要用 Path 对象建立。 - Menu 里如果不提供复制粘贴项,有时整个复制粘贴功能会失效。
- Mac 端 Menu 的第一个母菜单会被强制命名为应用名。
- 打包:Windows 的 icon 文件至少要 256×256,且不能硬转换;简单做法是用 Windows 自带的画图重新另存。
- Mac 只能打包 dmg;Windows 只能打包 msi 和 exe。
- Electron 关闭时不会自动 kill 它启动的 Node 进程。把 pid 存下来,关闭时手动清。
const platform = process.platform;
function killTask() {
try {
if (platform === "win32") {
for (let pid of pids) {
childProcess.exec(`taskkill /pid ${pid} /T /F`);
}
pids = [];
} else {
for (let pid of pids) {
process.kill(pid);
}
pids = [];
}
} catch (e) {
showInfo("pid not found");
}
clearInterval(timerId);
}
Node 的坑
- TypeScript 里要用
require之类的 Node 方法、或库里的某些方法,直接调用会编译报错。解决办法是declare:
declare function require(name: string);
declare var Vue: any;
- 箭头函数里的
this行为有时让人困惑。(2017-12-27 重写)
this 的真正机制是:Function 被调用时会自动调用 Function.call(<this>)。写 function X 的时候,JS 会把 this 指向当前的运行环境——某个 class 或者全局。看这段:
function a() {
this.d = 1;
function b() {
this.f = 2;
function c() {
this.g = 3;
}
}
}
函数 c 的 this 在被调用时是它自己的运行环境(也就是 b 这一层),所以这段在 c 是普通函数的情况下,相当于:
function a() {
this.d = 1;
function b() {
this.f = 2;
function c() {
b.g = 3;
}
}
}
换成箭头函数就不一样了:
function a() {
this.d = 1;
function b() {
this.f = 2;
let c = () => {
this.g = 3;
};
}
}
此时 c 的 this 和 b 的 this 指向同一处——也就是说 this.g = 3 改的是 a 那一层的 g,而不是 c 自己的新对象。
- TypeScript 不能用
obj.key直接给一个不存在的 key 赋值,但可以用obj["key"]用字符串绕过类型检查写入。
Vue 的坑
- 组件里执行回调必须用括号函数(普通方法)传,不能直接传方法引用,否则
this会跑。
API 的坑
- LoL 的 API 偶尔会错误返回 404。
- 当前游戏的 API 偶尔会给错时间字段,拿到响应之后先校验时间,不对就用真实的游戏时间替代。