Skip to content

Commit

Permalink
refactor some
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Feb 10, 2022
1 parent 98d55e6 commit 37ca8f6
Showing 1 changed file with 25 additions and 24 deletions.
49 changes: 25 additions & 24 deletions packages/plugin-react/src/jsx-runtime/restore-jsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,36 +25,37 @@ export async function restoreJSX(
return jsxNotFound
}

const reactJsxFragmentRE = new RegExp(
'\\b' + reactAlias + '\\.(Fragment)\\b',
'g'
)
const reactJsxCreatElementRE = new RegExp(
'\\b' + reactAlias + '\\.(createElement)\\b(\\([A-Z"]\\w)',
'g'
)

let hasCompiledJsx = false
code = code.replace(reactJsxFragmentRE, (_, prop) => {
hasCompiledJsx = true
// Replace with "React" so JSX can be reverse compiled.
return 'React.' + prop
})
code = code.replace(reactJsxCreatElementRE, (_, prop, prop2) => {
hasCompiledJsx = true
return 'React.' + prop + prop2
})

const fragmentPattern = `\\b${reactAlias}\\.Fragment\\b`
const createElementPattern = `\\b${reactAlias}\\.createElement\\(\\s*([A-Z"'][\\w$.]*["']?)`

// Replace the alias with "React" so JSX can be reverse compiled.
code = code
.replace(new RegExp(fragmentPattern, 'g'), () => {
hasCompiledJsx = true
return 'React.Fragment'
})
.replace(new RegExp(createElementPattern, 'g'), (original, component) => {
if (/^[a-z][\w$]*$/.test(component)) {
// Take care not to replace the alias for `createElement` calls whose
// component is a lowercased variable, since the `restoreJSX` Babel
// plugin leaves them untouched.
return original
}
hasCompiledJsx = true
return (
'React.createElement(' +
// Assume `Fragment` is equivalent to `React.Fragment` so modules
// that use `import {Fragment} from 'react'` are reverse compiled.
(component === 'Fragment' ? 'React.Fragment' : component)
)
})

if (!hasCompiledJsx) {
return jsxNotFound
}

// Support modules that use `import {Fragment} from 'react'`
code = code.replace(
/createElement\(Fragment,/g,
'createElement(React.Fragment,'
)

babelRestoreJSX ||= import('./babel-restore-jsx')

const result = await babel.transformAsync(code, {
Expand Down

0 comments on commit 37ca8f6

Please sign in to comment.