Skip to content

Commit 9a7073f

Browse files
committed
Improve isEsmId
1 parent 2f236ba commit 9a7073f

File tree

1 file changed

+33
-24
lines changed

1 file changed

+33
-24
lines changed

scripts/utils/packages.js

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -70,37 +70,46 @@ function isEsmId(id_, parentId_) {
7070
}
7171
const parentId = parentId_ ? resolveId(parentId_) : undefined
7272
const resolvedId = resolveId(id_, parentId)
73-
let result = false
7473
if (resolvedId.endsWith('.mjs')) {
75-
result = true
76-
} else if (
77-
!resolvedId.endsWith('.cjs') &&
78-
!resolvedId.endsWith('.json') &&
79-
!resolvedId.endsWith('.ts')
74+
return true
75+
}
76+
if (
77+
resolvedId.endsWith('.cjs') ||
78+
resolvedId.endsWith('.json') ||
79+
resolvedId.endsWith('.ts')
8080
) {
81-
let filepath
82-
if (path.isAbsolute(resolvedId)) {
83-
filepath = resolvedId
84-
} else if (parentId && isRelative(resolvedId)) {
85-
filepath = path.join(path.dirname(parentId), resolvedId)
86-
}
87-
if (filepath) {
88-
const pkgJsonPath = findUpSync('package.json', {
89-
cwd: path.dirname(resolvedId)
90-
})
91-
if (pkgJsonPath && require(pkgJsonPath)?.type === 'module') {
81+
return false
82+
}
83+
let filepath
84+
if (path.isAbsolute(resolvedId)) {
85+
filepath = resolvedId
86+
} else if (parentId && isRelative(resolvedId)) {
87+
filepath = path.join(path.dirname(parentId), resolvedId)
88+
}
89+
if (filepath) {
90+
const pkgJsonPath = findUpSync('package.json', {
91+
cwd: path.dirname(resolvedId)
92+
})
93+
if (pkgJsonPath) {
94+
const pkgJson = require(pkgJsonPath)
95+
const { exports: entryExports } = pkgJson
96+
if (
97+
pkgJson.type === 'module' &&
98+
!entryExports?.require &&
99+
!entryExports?.node?.default?.endsWith('.cjs')
100+
) {
92101
return true
93102
}
94-
try {
95-
new vm.Script(fs.readFileSync(resolvedId, 'utf8'))
96-
} catch (e) {
97-
if (e instanceof SyntaxError) {
98-
result = true
99-
}
103+
}
104+
try {
105+
new vm.Script(fs.readFileSync(resolvedId, 'utf8'))
106+
} catch (e) {
107+
if (e instanceof SyntaxError) {
108+
return true
100109
}
101110
}
102111
}
103-
return result
112+
return false
104113
}
105114

106115
function normalizeId(id) {

0 commit comments

Comments
 (0)