Skip to content

Commit

Permalink
fix: always export default
Browse files Browse the repository at this point in the history
  • Loading branch information
yejimeiming committed Oct 8, 2023
1 parent de0a56e commit 2eefcbc
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions src/generate-export.ts
Expand Up @@ -10,9 +10,14 @@ export function generateExport(analyzed: Analyzed): ExportsRuntime | null {
return null
}

const memberDefault = analyzed.exports
// Find `module.exports` or `exports.default`
.find(exp => exp.token.left === 'module' || exp.token.right === 'default')
// Since the `v0.10.0` version, it no longer matches whether there is an `exports.default` member, but exports directly.
// Because Vite will add `interop` related code snippets after the `import()` statement.
// `interop` snippets 👉 https://github.com/vitejs/vite/blob/v4.4.11/packages/vite/src/node/plugins/importAnalysis.ts#L874
// Check needs interop 👉 https://github.com/vitejs/vite/blob/v4.4.11/packages/vite/src/node/optimizer/index.ts#L1165-L1166
const memberDefault = {
declaration: 'const __CJS__export_default__ = (module.exports == null ? {} : module.exports).default || module.exports',
export: '__CJS__export_default__ as default',
}

let members = analyzed.exports
// Exclude `module.exports` and `exports.default`
Expand All @@ -21,14 +26,14 @@ export function generateExport(analyzed: Analyzed): ExportsRuntime | null {
// Remove duplicate export
members = [...new Set(members)]

const membersDeclaration = members.map(
m => `const __CJS__export_${m}__ = (module.exports == null ? {} : module.exports).${m}`,
)
const membersExport = members.map(m => `__CJS__export_${m}__ as ${m}`)
if (memberDefault) {
membersDeclaration.unshift(`const __CJS__export_default__ = (module.exports == null ? {} : module.exports).default || module.exports`)
membersExport.unshift('__CJS__export_default__ as default')
}
const membersDeclaration = [
memberDefault.declaration,
...members.map(m => `const __CJS__export_${m}__ = (module.exports == null ? {} : module.exports).${m}`),
]
const membersExport = [
memberDefault.export,
...members.map(m => `__CJS__export_${m}__ as ${m}`),
]

return {
polyfill: 'var module = { exports: {} }; var exports = module.exports;',
Expand Down

0 comments on commit 2eefcbc

Please sign in to comment.