Skip to content

Commit b165069

Browse files
committed
feat: use setPublicClassFields for useDefineForClassFields support
1 parent fa40dbc commit b165069

File tree

1 file changed

+59
-0
lines changed
  • packages/vite/src/node/plugins

1 file changed

+59
-0
lines changed

packages/vite/src/node/plugins/oxc.ts

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,55 @@ export async function transformWithOxc(
160160
)
161161
}
162162
}
163+
164+
const resolvedTsconfigTarget = resolveTsconfigTarget(
165+
loadedCompilerOptions.target,
166+
)
167+
const useDefineForClassFields =
168+
loadedCompilerOptions.useDefineForClassFields ??
169+
(resolvedTsconfigTarget === 'next' || resolvedTsconfigTarget >= 2022)
170+
resolvedOptions.assumptions ??= {}
171+
resolvedOptions.assumptions.setPublicClassFields =
172+
!useDefineForClassFields
173+
174+
// set target to es2022 or lower to enable class property transforms
175+
// https://github.com/oxc-project/oxc/issues/6735#issuecomment-2513866362
176+
if (!useDefineForClassFields) {
177+
let set = false
178+
if (!resolvedOptions.target) {
179+
resolvedOptions.target = 'es2022'
180+
set = true
181+
} else {
182+
const target = Array.isArray(resolvedOptions.target)
183+
? [...resolvedOptions.target]
184+
: resolvedOptions.target.split(',')
185+
const esTargetIndex = target.findIndex((t) =>
186+
t.toLowerCase().startsWith('es'),
187+
)
188+
if (esTargetIndex > 0) {
189+
const esTargetTrimmed = target[esTargetIndex].toLowerCase().slice(2)
190+
if (
191+
esTargetTrimmed === 'next' ||
192+
parseInt(esTargetTrimmed, 10) > 2022
193+
) {
194+
target[esTargetIndex] = 'es2022'
195+
set = true
196+
}
197+
} else {
198+
target.push('es2022')
199+
set = true
200+
}
201+
resolvedOptions.target = target
202+
}
203+
204+
if (set) {
205+
ctx?.warn(
206+
'target was modified to include ES2022' +
207+
' because useDefineForClassFields is set to false' +
208+
' and oxc does not support transforming useDefineForClassFields=false for ES2022+ yet',
209+
)
210+
}
211+
}
163212
} catch (e) {
164213
if (e instanceof TSConfckParseError) {
165214
// tsconfig could be out of root, make sure it is watched on dev
@@ -210,6 +259,16 @@ export async function transformWithOxc(
210259
}
211260
}
212261

262+
function resolveTsconfigTarget(target: string | undefined): number | 'next' {
263+
if (!target) return 5
264+
265+
const targetLowered = target.toLowerCase()
266+
if (!targetLowered.startsWith('es')) return 5
267+
268+
if (targetLowered === 'esnext') return 'next'
269+
return parseInt(targetLowered.slice(2))
270+
}
271+
213272
export function oxcPlugin(config: ResolvedConfig): Plugin {
214273
const options = config.oxc as OxcOptions
215274
const {

0 commit comments

Comments
 (0)