Skip to content

Commit

Permalink
fix: handle namespace import and dynamic import interop consistently (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
XiSenao committed Jan 18, 2024
1 parent 53452df commit ec8b420
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
2 changes: 1 addition & 1 deletion packages/vite/src/node/__tests__/plugins/import.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ describe('transformCjsImport', () => {
),
).toBe(
'import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js"; ' +
'const react = __vite__cjsImport0_react',
`const react = ((m) => m?.__esModule ? m : { ...typeof m === "object" && !Array.isArray(m) ? m : {}, default: m })(__vite__cjsImport0_react)`,
)
})

Expand Down
8 changes: 6 additions & 2 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,8 @@ export function createParseErrorInfo(
showCodeFrame: !probablyBinary,
}
}
// prettier-ignore
const interopHelper = (m: any) => m?.__esModule ? m : { ...(typeof m === 'object' && !Array.isArray(m) ? m : {}), default: m }

export function interopNamedImports(
str: MagicString,
Expand All @@ -870,7 +872,7 @@ export function interopNamedImports(
str.overwrite(
expStart,
expEnd,
`import('${rewrittenUrl}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))` +
`import('${rewrittenUrl}').then(m => (${interopHelper.toString()})(m.default))` +
getLineBreaks(exp),
{ contentOnly: true },
)
Expand Down Expand Up @@ -1006,7 +1008,9 @@ export function transformCjsImport(
const lines: string[] = [`import ${cjsModuleName} from "${url}"`]
importNames.forEach(({ importedName, localName }) => {
if (importedName === '*') {
lines.push(`const ${localName} = ${cjsModuleName}`)
lines.push(
`const ${localName} = (${interopHelper.toString()})(${cjsModuleName})`,
)
} else if (importedName === 'default') {
lines.push(
`const ${localName} = ${cjsModuleName}.__esModule ? ${cjsModuleName}.default : ${cjsModuleName}`,
Expand Down

0 comments on commit ec8b420

Please sign in to comment.