Nuxt/packages/kit/src/utils/cjs.ts

68 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-07-02 13:02:35 +00:00
import { join } from 'path'
2020-07-30 23:40:16 +00:00
export function isExternalDependency (id: string) {
2020-07-02 13:02:35 +00:00
return /[/\\]node_modules[/\\]/.test(id)
}
2020-07-30 23:40:16 +00:00
export function clearRequireCache (id: string) {
2020-07-02 13:02:35 +00:00
if (isExternalDependency(id)) {
return
}
const entry = getRequireCacheItem(id)
if (!entry) {
delete require.cache[id]
return
}
if (entry.parent) {
entry.parent.children = entry.parent.children.filter(e => e.id !== id)
}
for (const child of entry.children) {
clearRequireCache(child.id)
}
delete require.cache[id]
}
2020-07-30 23:40:16 +00:00
export function scanRequireTree (id: string, files = new Set<string>()) {
2020-07-02 13:02:35 +00:00
if (isExternalDependency(id) || files.has(id)) {
return files
}
const entry = getRequireCacheItem(id)
if (!entry) {
files.add(id)
return files
}
files.add(entry.id)
for (const child of entry.children) {
scanRequireTree(child.id, files)
}
return files
}
2020-07-30 23:40:16 +00:00
export function getRequireCacheItem (id: string) {
2020-07-02 13:02:35 +00:00
try {
return require.cache[id]
} catch (e) {
}
}
2020-07-30 23:40:16 +00:00
export function tryRequire (id: string) {
2020-07-02 13:02:35 +00:00
try {
return require(id)
} catch (e) {
}
}
2020-07-30 23:40:16 +00:00
export function getPKG (id: string) {
2020-07-02 13:02:35 +00:00
return tryRequire(join(id, 'package.json'))
}