Skip to content

Commit 05b91cd

Browse files
authored
fix(plugin-react): support import namespace in parseReactAlias (#5313)
1 parent f09299c commit 05b91cd

File tree

2 files changed

+65
-4
lines changed

2 files changed

+65
-4
lines changed

packages/plugin-react/src/jsx-runtime/restore-jsx.spec.ts

+62-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,67 @@
11
import * as babel from '@babel/core'
22
import { describe, expect, it } from 'vitest'
3-
import { restoreJSX } from './restore-jsx'
3+
import { parseReactAlias, restoreJSX } from './restore-jsx'
4+
5+
describe('parseReactAlias', () => {
6+
it('handles cjs require', () => {
7+
expect(parseReactAlias(`const React = require("react")`))
8+
.toMatchInlineSnapshot(`
9+
[
10+
"React",
11+
true,
12+
]
13+
`)
14+
})
15+
16+
it('handles cjs require (minified)', () => {
17+
expect(parseReactAlias(`var F=require('foo');var R=require('react')`))
18+
.toMatchInlineSnapshot(`
19+
[
20+
"R",
21+
true,
22+
]
23+
`)
24+
})
25+
26+
it('does not handle destructured cjs require', () => {
27+
expect(parseReactAlias(`var {createElement} = require("react")`))
28+
.toMatchInlineSnapshot(`
29+
[
30+
undefined,
31+
false,
32+
]
33+
`)
34+
})
35+
36+
it('handles esm import', () => {
37+
expect(parseReactAlias(`import React from 'react'`)).toMatchInlineSnapshot(`
38+
[
39+
"React",
40+
false,
41+
]
42+
`)
43+
})
44+
45+
it('handles esm import namespace', () => {
46+
expect(parseReactAlias(`import * as React from "react"`))
47+
.toMatchInlineSnapshot(`
48+
[
49+
"React",
50+
false,
51+
]
52+
`)
53+
})
54+
55+
it('does not handle destructured esm import', () => {
56+
expect(parseReactAlias(`import {createElement} from "react"`))
57+
.toMatchInlineSnapshot(`
58+
[
59+
undefined,
60+
false,
61+
]
62+
`)
63+
})
64+
})
465

566
async function jsx(sourceCode: string) {
667
const [ast] = await restoreJSX(babel, sourceCode, 'test.js')

packages/plugin-react/src/jsx-runtime/restore-jsx.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -79,16 +79,16 @@ export async function restoreJSX(
7979
return [result?.ast, isCommonJS]
8080
}
8181

82-
function parseReactAlias(
82+
export function parseReactAlias(
8383
code: string
8484
): [alias: string | undefined, isCommonJS: boolean] {
8585
let match = code.match(
86-
/\b(var|let|const) +(\w+) *= *require\(["']react["']\)/
86+
/\b(var|let|const)\s+([^=\{\s]+)\s*=\s*require\(["']react["']\)/
8787
)
8888
if (match) {
8989
return [match[2], true]
9090
}
91-
match = code.match(/^import (\w+).+? from ["']react["']/m)
91+
match = code.match(/^import\s+(?:\*\s+as\s+)?(\w+).+?\bfrom\s*["']react["']/m)
9292
if (match) {
9393
return [match[1], false]
9494
}

0 commit comments

Comments
 (0)