Skip to content

Commit 0bdf788

Browse files
committed
chore: tweaks
1 parent 8d352f6 commit 0bdf788

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

src/index.js

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
1+
// 1. find to ExportsModuleDeclaration(`Object.defineProperty(exports, "__esModule", {value: true});`)
2+
// 2. find to ExportsAssignmentExpression(`exports.default`, `exports.foo` etc)
3+
// 3. add `module.exports` if exists only `exports.default` assignment
4+
// The above works after executing `preset-env`(transform-es2015-modules-*) in `Plugin.post`
5+
16
module.exports = ({template, types}) => {
27
let pluginOptions
3-
const visitor = {
8+
const ExportsModuleDeclarationVisitor = {
49
CallExpression: {
510
exit (path) {
6-
// Not `Object.defineProperty`, skip
7-
if (!path.get('callee.object').node) {
8-
return
9-
}
10-
1111
if (isExportsModuleDeclaration(path)) {
1212
const finder = new ExportFinder(path)
1313

1414
if (finder.isOnlyDefaultExport()) {
15-
const root = finder.getRootNode()
15+
const rootPath = finder.getRootPath()
1616

17-
// HACK: `program.node.body.push` instead of pushContainer(due doesn't work in Plugin.post)
18-
root.node.body.push(template('module.exports = exports.default')())
17+
// HACK: `path.node.body.push` instead of path.pushContainer(due doesn't work in Plugin.post)
18+
rootPath.node.body.push(template('module.exports = exports.default')())
1919
if (pluginOptions.addDefaultProperty) {
20-
root.node.body.push(template('module.exports.default = exports.default')())
20+
rootPath.node.body.push(template('module.exports.default = exports.default')())
2121
}
2222
}
2323
}
@@ -33,12 +33,17 @@ module.exports = ({template, types}) => {
3333
}
3434
},
3535
post (fileMap) {
36-
fileMap.path.traverse(visitor)
36+
fileMap.path.traverse(ExportsModuleDeclarationVisitor)
3737
}
3838
}
3939
}
4040

4141
function isExportsModuleDeclaration (path) {
42+
// Not `Object.defineProperty`, skip
43+
if (!path.get('callee.object').node) {
44+
return false
45+
}
46+
4247
const callee = `${path.get('callee.object.name').node}.${path.get('callee.property.name').node}`
4348
const args = path.get('arguments').map(path => {
4449
if (path.isStringLiteral()) {
@@ -59,11 +64,11 @@ class ExportFinder {
5964
this.hasExportDefault = false
6065
this.hasExportNamed = false
6166
}
62-
getRootNode () {
67+
getRootPath () {
6368
return this.path.parentPath.parentPath
6469
}
6570
isOnlyDefaultExport () {
66-
this.getRootNode().get('body').forEach((path) => {
71+
this.getRootPath().get('body').forEach((path) => {
6772
if (path.isVariableDeclaration()) {
6873
this.findExport(path.get('declarations.0'), 'init')
6974
} else {

0 commit comments

Comments
 (0)