Skip to content

Commit e8f84e4

Browse files
committed
naive module.parent implementation
1 parent b450202 commit e8f84e4

File tree

4 files changed

+29
-0
lines changed

4 files changed

+29
-0
lines changed

index.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,13 @@ function parseModule (row, index, rows) {
114114
})
115115
}
116116

117+
rows.forEach(function (p) {
118+
var deps = Object.values(p.deps).map(String)
119+
if (deps.includes(String(row.id)) && !row.parent) {
120+
row.parent = p
121+
}
122+
})
123+
117124
row.ast = ast
118125
row.isSimpleExport = isSimpleExport
119126
row.exportsName = moduleExportsName
@@ -163,6 +170,12 @@ function rewriteModule (row, i, rows) {
163170
// rewrite `typeof module` to `"object"`
164171
if (node.parent.type === 'UnaryExpression' && node.parent.operator === 'typeof') {
165172
node.parent.edit.update('"object"')
173+
} else if (isModuleParent(node.parent)) {
174+
if (row.entry) {
175+
node.parent.edit.update('null')
176+
} else {
177+
node.parent.edit.update('({})')
178+
}
166179
} else {
167180
renameIdentifier(node, moduleBaseName)
168181
}
@@ -398,6 +411,12 @@ function isModuleExports (node) {
398411
(node.property.type === 'Identifier' && node.property.name === 'exports' ||
399412
node.property.type === 'Literal' && node.property.value === 'exports')
400413
}
414+
function isModuleParent (node) {
415+
return node.type === 'MemberExpression' &&
416+
node.object.type === 'Identifier' && node.object.name === 'module' &&
417+
(node.property.type === 'Identifier' && node.property.name === 'parent' ||
418+
node.property.type === 'Literal' && node.property.value === 'parent')
419+
}
401420
function isRequire (node) {
402421
return node.type === 'CallExpression' &&
403422
node.callee.type === 'Identifier' && node.callee.name === 'require'

test/module-parent/app.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
require('./child')
2+
3+
if (module.parent) {
4+
throw Error('should be entry point')
5+
}

test/module-parent/child.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
if (module.parent) {
2+
module.exports = 'required'
3+
} else {
4+
module.exports = 'entry point'
5+
}

test/module-parent/expected.js

Whitespace-only changes.

0 commit comments

Comments
 (0)