diff --git a/packages/vite/src/node/__tests__/plugins/esbuild.spec.ts b/packages/vite/src/node/__tests__/plugins/esbuild.spec.ts index 8992000da101a5..0d6d81af898e5a 100644 --- a/packages/vite/src/node/__tests__/plugins/esbuild.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/esbuild.spec.ts @@ -383,6 +383,21 @@ describe('transformWithEsbuild', () => { const actual = await transformClassCode('es2022', {}) expect(actual).toBe(defineForClassFieldsFalseTransformedCode) }) + + test('useDefineForClassFields: false and static property should not be transpile to static block', async () => { + const result = await transformWithEsbuild( + ` + class foo { + static bar = 'bar' + } + `, + 'bar.ts', + { + target: 'esnext', + }, + ) + expect(result?.code).not.toContain('static {') + }) }) }) diff --git a/packages/vite/src/node/plugins/esbuild.ts b/packages/vite/src/node/plugins/esbuild.ts index 1e2f5751600bf8..d2bf848437a915 100644 --- a/packages/vite/src/node/plugins/esbuild.ts +++ b/packages/vite/src/node/plugins/esbuild.ts @@ -96,6 +96,7 @@ export async function transformWithEsbuild( } let tsconfigRaw = options?.tsconfigRaw + const fallbackSupported: Record = {} // if options provide tsconfigRaw in string, it takes highest precedence if (typeof tsconfigRaw !== 'string') { @@ -150,6 +151,15 @@ export async function transformWithEsbuild( compilerOptions.experimentalDecorators = true } + // Compat with esbuild 0.17 where static properties are transpiled to + // static blocks when `useDefineForClassFields` is false. Its support + // is not great yet, so temporarily disable it for now. + // TODO: Remove this in Vite 5, don't pass hardcoded `esnext` target + // to `transformWithEsbuild` in the esbuild plugin. + if (compilerOptions.useDefineForClassFields !== true) { + fallbackSupported['class-static-blocks'] = false + } + // esbuild uses tsconfig fields when both the normal options and tsconfig was set // but we want to prioritize the normal options if (options) { @@ -172,6 +182,10 @@ export async function transformWithEsbuild( ...options, loader, tsconfigRaw, + supported: { + ...fallbackSupported, + ...options?.supported, + }, } // Some projects in the ecosystem are calling this function with an ESBuildOptions