-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2eefcbc
commit 63324c2
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import type { Analyzed } from './analyze' | ||
|
||
export interface ExportsRuntime { | ||
polyfill: string | ||
exportDeclaration: string | ||
} | ||
|
||
export function generateExport(analyzed: Analyzed): ExportsRuntime | null { | ||
if (!analyzed.exports.length) { | ||
return null | ||
} | ||
|
||
const memberDefault = analyzed.exports | ||
// Find `module.exports` or `exports.default` | ||
.find(exp => exp.token.left === 'module' || exp.token.right === 'default') | ||
|
||
let members = analyzed.exports | ||
// Exclude `module.exports` and `exports.default` | ||
.filter(exp => exp.token.left !== 'module' && exp.token.right !== 'default') | ||
.map(exp => exp.token.right) | ||
// 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') | ||
} | ||
|
||
return { | ||
polyfill: 'var module = { exports: {} }; var exports = module.exports;', | ||
exportDeclaration: ` | ||
${membersDeclaration.join(';\n')}; | ||
export { | ||
${membersExport.join(',\n ')}, | ||
} | ||
`.trim(), | ||
} | ||
} |