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 c913bc1
Showing 1 changed file with 22 additions and 22 deletions.
44 changes: 22 additions & 22 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,36 @@ 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) => {

// Replace the alias with "React" so JSX can be reverse compiled.
code = code.replace(new RegExp(`\\b${reactAlias}\\.Fragment\\b`, 'g'), () => {
hasCompiledJsx = true
return 'React.' + prop + prop2
return 'React.Fragment'
})

// Take care not to replace the alias for `createElement` calls whose
// component is a lowercased variable, since the `restoreJSX` Babel
// plugin leaves them untouched.
code = code.replace(
new RegExp(
`\\b${reactAlias}\\.createElement\\(\s*([A-Z"']\\w*["']?)\\b`,
'g'
),
(_, component) => {
hasCompiledJsx = true
return (
'React.createElement(' +
// Support modules that use `import {Fragment} from 'react'`
(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 c913bc1

Please sign in to comment.