Skip to content

Commit

Permalink
fix: should respect legacy decorators (#67)
Browse files Browse the repository at this point in the history
Co-authored-by: Sukka <[email protected]>
  • Loading branch information
nonzzz and SukkaW authored Oct 7, 2024
1 parent ef2d387 commit a477f50
Show file tree
Hide file tree
Showing 7 changed files with 381 additions and 62 deletions.
8 changes: 4 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
} from '@swc/core';
import createDeepMerge from '@fastify/deepmerge';

import { getOptions, getEnableExperimentalDecorators } from './options';
import { getOptions, checkIsLegacyTypeScript } from './options';

import type { Plugin as VitePlugin } from 'vite';

Expand Down Expand Up @@ -67,7 +67,7 @@ function swc(options: PluginOptions = {}): RollupPlugin {
return null;
};

const enableExperimentalDecorators = getEnableExperimentalDecorators();
const isLegacyTypeScript = checkIsLegacyTypeScript();

return {
name: 'swc',
Expand Down Expand Up @@ -127,7 +127,7 @@ function swc(options: PluginOptions = {}): RollupPlugin {
parser: {
syntax: isTypeScript ? 'typescript' : 'ecmascript',
[isTypeScript ? 'tsx' : 'jsx']: isTypeScript ? isTsx : isJsx,
decorators: enableExperimentalDecorators || tsconfigOptions.experimentalDecorators
decorators: !isLegacyTypeScript || tsconfigOptions.experimentalDecorators
},
transform: {
decoratorMetadata: tsconfigOptions.emitDecoratorMetadata,
Expand All @@ -140,7 +140,7 @@ function swc(options: PluginOptions = {}): RollupPlugin {
pragmaFrag: tsconfigOptions.jsxFragmentFactory,
development: tsconfigOptions.jsx === 'react-jsxdev' ? true : undefined
},
decoratorVersion: enableExperimentalDecorators ? '2022-03' : '2021-12'
decoratorVersion: isLegacyTypeScript ? '2021-12' : (tsconfigOptions.experimentalDecorators ? '2021-12' : '2022-03')
},
target: tsconfigOptions.target?.toLowerCase() as JscTarget | undefined,
baseUrl: tsconfigOptions.baseUrl,
Expand Down
6 changes: 3 additions & 3 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,14 @@ export const getOptions = (
return compilerOptions;
};

export const getEnableExperimentalDecorators = () => {
export const checkIsLegacyTypeScript = () => {
try {
// @ts-expect-error -- It's required to using 'import.mtea.url' but i don't want to change the tsconfig.
const tsPath = resolve('typescript/package.json', import.meta.url);
const { version } = JSON.parse(fs.readFileSync(fileURLToPath(tsPath), 'utf-8'));
const [major] = version.split('.');
// Only check experimental decorators for TypeScript 5+
return +major >= 5;
// typescript 5+ enable experimentalDecorators by default so we think it's not legacy
return +major < 5;
} catch {
return false;
}
Expand Down
Loading

0 comments on commit a477f50

Please sign in to comment.