We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
今天(2024-09-29)排查的一个编译问题,关键词: esbuild、decorators、esnext、mobx
如下代码被 esbuild 编译时
import { observable } from 'mobx' class MyStore { @observable data = [] } const instance = new MyStore() instance.data.toJS();
Case1: 当 target: esnext 时被编译为,此时 data.toJS() 会抛错 ❌,data.toJS is not a function
import { observable } from 'mobx' class MyStore { + data = []; } __decorateClass([ observable ], MyStore.prototype, "data", 2); const instance = new MyStore() instance.data.toJS();
Case2: 当 target: es6 时被编译为,代码正常运行 ✅
import { observable } from 'mobx' class MyStore { + constructor() { + this.data = []; + } } __decorateClass([ observable ], MyStore.prototype, "data", 2); const instance = new MyStore() instance.data.toJS();
这两种写法在 ChatGPT 看来是几乎等价的,Case1 是新语法,Case2 是旧语法,那么造成 Case1 代码运行异常的原因是什么 ?
两者的共同点是使用 __decorateClass 函数中的 Object.defineProperty 给原形链对象 MyStore.prototype 的 key 设置拦截函数
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __decorateClass = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; };
不同点是
结论: Case2 会触发原型链上的拦截函数 setter,Case1 不会触发
The text was updated successfully, but these errors were encountered:
No branches or pull requests
如下代码被 esbuild 编译时
Case1: 当 target: esnext 时被编译为,此时 data.toJS() 会抛错 ❌,data.toJS is not a function
import { observable } from 'mobx' class MyStore { + data = []; } __decorateClass([ observable ], MyStore.prototype, "data", 2); const instance = new MyStore() instance.data.toJS();
Case2: 当 target: es6 时被编译为,代码正常运行 ✅
这两种写法在 ChatGPT 看来是几乎等价的,Case1 是新语法,Case2 是旧语法,那么造成 Case1 代码运行异常的原因是什么 ?
两者的共同点是使用 __decorateClass 函数中的 Object.defineProperty 给原形链对象 MyStore.prototype 的 key 设置拦截函数
不同点是
结论: Case2 会触发原型链上的拦截函数 setter,Case1 不会触发
The text was updated successfully, but these errors were encountered: