|
| 1 | +import type { RsbuildConfig, RsbuildPlugin } from '@rsbuild/core'; |
| 2 | +import type { TsconfigCompilerOptions } from './types'; |
| 3 | +import { color } from './utils/helper'; |
| 4 | +import { logger } from './utils/logger'; |
| 5 | + |
| 6 | +type PluginReactOptions = { |
| 7 | + tsconfigCompilerOptions?: TsconfigCompilerOptions; |
| 8 | +}; |
| 9 | + |
| 10 | +const mapTsconfigJsxToSwcJsx = (jsx: string | undefined): string | null => { |
| 11 | + if (jsx === undefined) { |
| 12 | + // 'preserve' is the default value of tsconfig.compilerOptions.jsx |
| 13 | + return null; |
| 14 | + } |
| 15 | + |
| 16 | + // Calculate a corresponding SWC JSX config if tsconfig.compilerOptions.jsx is set to React related option. |
| 17 | + // Return `null` stands for no need to check. |
| 18 | + switch (jsx) { |
| 19 | + case 'react-jsx': |
| 20 | + case 'react-jsxdev': |
| 21 | + return 'automatic'; |
| 22 | + case 'react': |
| 23 | + return 'classic'; |
| 24 | + case 'preserve': |
| 25 | + case 'react-native': |
| 26 | + // SWC JSX does not support `preserve` as of now. |
| 27 | + return null; |
| 28 | + default: |
| 29 | + return null; |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | +const checkJsx = ({ |
| 34 | + tsconfigCompilerOptions, |
| 35 | +}: PluginReactOptions): RsbuildPlugin => ({ |
| 36 | + name: 'rsbuild:lib-check', |
| 37 | + setup(api) { |
| 38 | + api.onBeforeEnvironmentCompile(({ environment }) => { |
| 39 | + const config = api.getNormalizedConfig({ |
| 40 | + environment: environment.name, |
| 41 | + }); |
| 42 | + const swc = config.tools.swc; |
| 43 | + const tsconfigJsx = tsconfigCompilerOptions?.jsx; |
| 44 | + if (swc && !Array.isArray(swc) && typeof swc !== 'function') { |
| 45 | + const swcReactRuntime = swc?.jsc?.transform?.react?.runtime || null; |
| 46 | + const mapped = mapTsconfigJsxToSwcJsx(tsconfigJsx); |
| 47 | + if (mapped !== swcReactRuntime) { |
| 48 | + logger.warn( |
| 49 | + `JSX runtime is set to ${color.green(`${JSON.stringify(swcReactRuntime)}`)} in SWC, but got ${color.green(`${JSON.stringify(tsconfigJsx)}`)} in tsconfig.json. This may cause unexpected behavior, considering aligning them.`, |
| 50 | + ); |
| 51 | + } |
| 52 | + } |
| 53 | + }); |
| 54 | + }, |
| 55 | +}); |
| 56 | + |
| 57 | +export const composeCheckConfig = ( |
| 58 | + compilerOptions: TsconfigCompilerOptions, |
| 59 | +): RsbuildConfig => { |
| 60 | + return { plugins: [checkJsx({ tsconfigCompilerOptions: compilerOptions })] }; |
| 61 | +}; |
0 commit comments