Skip to content

Commit b303b0d

Browse files
Vite plugin - fix field initializer placement in constructor body
1 parent 585669d commit b303b0d

2 files changed

Lines changed: 26 additions & 6 deletions

File tree

packages/devextreme/build/vite-plugin-devextreme.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,22 @@ describe('moveFieldInitializersToConstructor', () => {
128128
const out = transform(input, moveFieldInitializersToConstructor);
129129
expect(out).toMatch(/constructor\(\)\s*\{\s*this\.foo\s*=\s*42;\s*const\s+x\s*=\s*1;\s*this\.x\s*=\s*x/);
130130
});
131+
132+
test('inserts right after super() when a non-matching statement precedes param-property assignment', () => {
133+
const input = `
134+
class Derived extends Base {
135+
cached = 'init';
136+
constructor(x) {
137+
super();
138+
this.doSetup();
139+
this.x = x;
140+
}
141+
}
142+
`;
143+
const out = transform(input, moveFieldInitializersToConstructor);
144+
expect(out).toMatch(/super\(\);\s*this\.cached\s*=\s*'init';\s*this\.doSetup\(\);\s*this\.x\s*=\s*x/);
145+
expect(out).not.toMatch(/this\.x\s*=\s*x;\s*this\.cached\s*=\s*'init'/);
146+
});
131147
});
132148

133149
describe('removeUninitializedClassFields', () => {

packages/devextreme/build/vite-plugin-devextreme.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,15 @@ export function moveFieldInitializersToConstructor(): unknown {
8989

9090
const ctorBody = ctor.body!.body as Stmt[];
9191

92-
let insertAt = 0;
93-
for (let i = 0; i < ctorBody.length; i += 1) {
94-
const stmt = ctorBody[i];
95-
const isSuperCall = stmt.type === 'ExpressionStatement'
92+
const superCallIdx = ctorBody.findIndex(
93+
(stmt) => stmt.type === 'ExpressionStatement'
9694
&& stmt.expression?.type === 'CallExpression'
97-
&& stmt.expression.callee?.type === 'Super';
95+
&& stmt.expression.callee?.type === 'Super',
96+
);
97+
98+
let insertAt = superCallIdx !== -1 ? superCallIdx + 1 : 0;
99+
while (insertAt < ctorBody.length) {
100+
const stmt = ctorBody[insertAt];
98101
const isParamPropertyAssignment = stmt.type === 'ExpressionStatement'
99102
&& stmt.expression?.type === 'AssignmentExpression'
100103
&& stmt.expression.operator === '='
@@ -104,7 +107,8 @@ export function moveFieldInitializersToConstructor(): unknown {
104107
&& stmt.expression.left.property?.name === stmt.expression.right.name
105108
&& paramNames.has(stmt.expression.right.name!);
106109

107-
if (isSuperCall || isParamPropertyAssignment) insertAt = i + 1;
110+
if (!isParamPropertyAssignment) break;
111+
insertAt += 1;
108112
}
109113

110114
ctorBody.splice(insertAt, 0, ...(assignments as Stmt[]));

0 commit comments

Comments
 (0)