Skip to content
New issue

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

fix: Computed properties should keep original definition order #15232

Merged
merged 12 commits into from
Dec 5, 2022
Prev Previous commit
Next Next commit
Better helper fallback
  • Loading branch information
liuxingbaoyu authored and SuperSodaSea committed Dec 2, 2022
commit 8a6ccb4b879e33de51e0c98d80157c1edaee93cf
2 changes: 1 addition & 1 deletion packages/babel-core/src/transformation/file/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ export default class File {
});

nodes.forEach(node => {
// @ts-expect-error Fixeme: document _compact node property
// @ts-expect-error Fixme: document _compact node property
node._compact = true;
});

Expand Down
33 changes: 16 additions & 17 deletions packages/babel-plugin-transform-computed-properties/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ type PropertyInfo = {
state: PluginPass;
};

const DefineAccessorHelper = template.expression.ast`
SuperSodaSea marked this conversation as resolved.
Show resolved Hide resolved
function (type, obj, key, fn) {
var desc = { configurable: true, enumerable: true };
desc[type] = fn;
return Object.defineProperty(obj, key, desc);
}`;
// @ts-expect-error undocumented _compact node property
DefineAccessorHelper._compact = true;

export default declare((api, options: Options) => {
api.assertVersion(7);

Expand All @@ -40,24 +49,14 @@ export default declare((api, options: Options) => {
} else {
// Fallback for @babel/helpers <= 7.20.6, manually add helper function
SuperSodaSea marked this conversation as resolved.
Show resolved Hide resolved
const file = state.file;
helper = file.declarations["defineAccessor"];
helper = file.get("fallbackDefineAccessorHelper");
if (!helper) {
helper = file.declarations["defineAccessor"] =
file.scope.generateUidIdentifier("defineAccessor");

const helperDeclaration = template.statement.ast`
function ${helper}(type, obj, key, fn) {
var desc = { configurable: true, enumerable: true };
desc[type] = fn;
return Object.defineProperty(obj, key, desc);
}
`;
const helperPath = file.path.unshiftContainer(
"body",
helperDeclaration,
)[0];
// TODO: NodePath#unshiftContainer should automatically register new bindings.
file.scope.registerDeclaration(helperPath);
const id = file.scope.generateUidIdentifier("defineAccessor");
file.scope.push({
id,
init: DefineAccessorHelper,
});
file.set("fallbackDefineAccessorHelper", (helper = id));
}
helper = t.cloneNode(helper);
}
Expand Down