Skip to content

Commit

Permalink
add "default" named export to CJS
Browse files Browse the repository at this point in the history
  • Loading branch information
d-fischer committed Jul 3, 2020
1 parent 7be36b8 commit 31ae209
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,14 +118,18 @@ function run(filepath, isMode) {
const isDefault = /export default/.test(ESM);

let CJS = imports(ESM)
.replace(/(^|\s|;)export default/, '$1module.exports =')
.replace(/(^|\s|;)export default/, '$1var __defaultExport =')
.replace(/(^|\s|;)export (const|(?:async )?function|class|let|var) (.+?)(?=(\(|\s|\=))/gi, (_, x, type, name) => {
return keys.push(name) && `${x}${type} ${name}`;
})
.replace(/(^|\s|;)export \{(.+?)}(?=(;|\s|$))/, (_, x, names) => {
return keys.push(...(names.split(',').map(name => name.trim()))) && x;
return keys.push(...(names.split(',').map(name => name.trim()))) && '';
});

if (isDefault) {
CJS += `\nmodule.exports = __defaultExport;\nmodule.exports.default = __defaultExport;`
}

if (keys.length > 0) {
keys.sort().forEach(key => {
CJS += `\nmodule.exports.${key} = ${key};`;
Expand Down

0 comments on commit 31ae209

Please sign in to comment.