Skip to content

Commit 63324c2

Browse files
committed
chore: backup export
1 parent 2eefcbc commit 63324c2

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

‎src/generate-export-v0.9.0.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import type { Analyzed } from './analyze'
2+
3+
export interface ExportsRuntime {
4+
polyfill: string
5+
exportDeclaration: string
6+
}
7+
8+
export function generateExport(analyzed: Analyzed): ExportsRuntime | null {
9+
if (!analyzed.exports.length) {
10+
return null
11+
}
12+
13+
const memberDefault = analyzed.exports
14+
// Find `module.exports` or `exports.default`
15+
.find(exp => exp.token.left === 'module' || exp.token.right === 'default')
16+
17+
let members = analyzed.exports
18+
// Exclude `module.exports` and `exports.default`
19+
.filter(exp => exp.token.left !== 'module' && exp.token.right !== 'default')
20+
.map(exp => exp.token.right)
21+
// Remove duplicate export
22+
members = [...new Set(members)]
23+
24+
const membersDeclaration = members.map(
25+
m => `const __CJS__export_${m}__ = (module.exports == null ? {} : module.exports).${m}`,
26+
)
27+
const membersExport = members.map(m => `__CJS__export_${m}__ as ${m}`)
28+
if (memberDefault) {
29+
membersDeclaration.unshift(`const __CJS__export_default__ = (module.exports == null ? {} : module.exports).default || module.exports`)
30+
membersExport.unshift('__CJS__export_default__ as default')
31+
}
32+
33+
return {
34+
polyfill: 'var module = { exports: {} }; var exports = module.exports;',
35+
exportDeclaration: `
36+
${membersDeclaration.join(';\n')};
37+
export {
38+
${membersExport.join(',\n ')},
39+
}
40+
`.trim(),
41+
}
42+
}

0 commit comments

Comments
 (0)