Skip to content

Commit

Permalink
refactor: improve logic to set react jsx type (#681)
Browse files Browse the repository at this point in the history
  • Loading branch information
PeachScript committed Jul 23, 2023
1 parent 611f00c commit 6a87756
Showing 1 changed file with 26 additions and 27 deletions.
53 changes: 26 additions & 27 deletions src/builder/utils.ts
Expand Up @@ -19,40 +19,39 @@ export function addSourceMappingUrl(code: string, loc: string) {
}

export function getBaseTransformReactOpts(pkg: IApi['pkg'], cwd: string) {
let isNewJSX: boolean;
let opts: Record<string, any> = {};
const reactVer = Object.assign(
{},
pkg.dependencies,
pkg.peerDependencies,
).react;
let opts: Record<string, any> = {};

if (reactVer) {
let isNewJSX: boolean;
const tsconfig = getTsconfig(cwd);

/* istanbul ignore else -- @preserve */
if (tsconfig?.options?.jsx !== undefined) {
// respect tsconfig first, `4` means `react-jsx`
isNewJSX = tsconfig.options?.jsx === 4;
} else {
// fallback to match react versions which support new JSX transform
// ref: https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#how-to-upgrade-to-the-new-jsx-transform
isNewJSX = semver.subset(
reactVer,
'>=17.0.0-0||^16.14.0||^15.7.0||^0.14.10',
);
}

opts = {
// force use production mode, to make sure dist of dev/build are consistent
// ref: https://github.com/umijs/umi/blob/6f63435d42f8ef7110f73dcf33809e6cda750332/packages/babel-preset-umi/src/index.ts#L45
development: false,
// set jsx runtime automatically
runtime: isNewJSX ? 'automatic' : 'classic',
...(isNewJSX ? {} : { importSource: undefined }),
};
const tsconfig = getTsconfig(cwd);

/* istanbul ignore else -- @preserve */
if (tsconfig?.options?.jsx !== undefined) {
// respect tsconfig first, `4` means `react-jsx`
isNewJSX = tsconfig.options?.jsx === 4;
} else if (reactVer) {
// fallback to match react versions which support new JSX transform
// ref: https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#how-to-upgrade-to-the-new-jsx-transform
isNewJSX = semver.subset(
reactVer,
'>=17.0.0-0||^16.14.0||^15.7.0||^0.14.10',
);
} else {
return false;
}

opts = {
// force use production mode, to make sure dist of dev/build are consistent
// ref: https://github.com/umijs/umi/blob/6f63435d42f8ef7110f73dcf33809e6cda750332/packages/babel-preset-umi/src/index.ts#L45
development: false,
// set jsx runtime automatically
runtime: isNewJSX ? 'automatic' : 'classic',
...(isNewJSX ? {} : { importSource: undefined }),
};

return opts;
}

Expand Down

0 comments on commit 6a87756

Please sign in to comment.