forked from egoist/tsup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.ts
118 lines (104 loc) · 2.55 KB
/
load.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import fs from 'fs'
import JoyCon from 'joycon'
import path from 'path'
import { bundleRequire } from 'bundle-require'
import { defineConfig } from './'
import { jsoncParse } from './utils'
const joycon = new JoyCon()
const loadJson = async (filepath: string) => {
try {
return jsoncParse(await fs.promises.readFile(filepath, 'utf8'))
} catch (error) {
if (error instanceof Error) {
throw new Error(
`Failed to parse ${path.relative(process.cwd(), filepath)}: ${
error.message
}`
)
} else {
throw error
}
}
}
const jsonLoader = {
test: /\.json$/,
load(filepath: string) {
return loadJson(filepath)
},
}
joycon.addLoader(jsonLoader)
export async function loadTsupConfig(
cwd: string,
configFile?: string
): Promise<{ path?: string; data?: ReturnType<typeof defineConfig> }> {
const configJoycon = new JoyCon()
const configPath = await configJoycon.resolve({
files: configFile
? [configFile]
: [
'tsup.config.ts',
'tsup.config.js',
'tsup.config.cjs',
'tsup.config.mjs',
'tsup.config.json',
'package.json',
],
cwd,
stopDir: path.parse(cwd).root,
packageKey: 'tsup',
})
if (configPath) {
if (configPath.endsWith('.json')) {
let data = await loadJson(configPath)
if (configPath.endsWith('package.json')) {
data = data.tsup
}
if (data) {
return { path: configPath, data }
}
return {}
}
const config = await bundleRequire({
filepath: configPath,
})
return {
path: configPath,
data: config.mod.tsup || config.mod.default || config.mod,
}
}
return {}
}
export async function loadPkg(cwd: string, clearCache: boolean = false) {
if (clearCache) {
joycon.clearCache()
}
const { data } = await joycon.load(['package.json'], cwd, path.dirname(cwd))
return data || {}
}
/*
* Production deps should be excluded from the bundle
*/
export async function getProductionDeps(
cwd: string,
clearCache: boolean = false
) {
const data = await loadPkg(cwd, clearCache)
const deps = Array.from(
new Set([
...Object.keys(data.dependencies || {}),
...Object.keys(data.peerDependencies || {}),
])
)
return deps
}
/**
* Use this to determine if we should rebuild when package.json changes
*/
export async function getAllDepsHash(cwd: string) {
const data = await loadPkg(cwd, true)
return JSON.stringify({
...data.dependencies,
...data.peerDependencies,
...data.devDependencies,
})
}