/
build.ts
191 lines (163 loc) · 5.35 KB
/
build.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import Module from 'module'
import { resolve, basename } from 'pathe'
import type { PackageJson } from 'pkg-types'
import chalk from 'chalk'
import consola from 'consola'
import { defu } from 'defu'
import { createHooks } from 'hookable'
import prettyBytes from 'pretty-bytes'
import mkdirp from 'mkdirp'
import { dumpObject, rmdir, tryRequire, resolvePreset } from './utils'
import type { BuildContext, BuildConfig, BuildOptions } from './types'
import { validatePackage, validateDependencies } from './validate'
import { rollupBuild } from './builder/rollup'
import { typesBuild } from './builder/untyped'
import { mkdistBuild } from './builder/mkdist'
export async function build (rootDir: string, stub: boolean, inputConfig: BuildConfig = {}) {
// Determine rootDir
rootDir = resolve(process.cwd(), rootDir || '.')
// Read build.config and package.json
const buildConfig: BuildConfig = tryRequire('./build.config', rootDir) || {}
const pkg: PackageJson & Record<'unbuild' | 'build', BuildConfig> = tryRequire('./package.json', rootDir)
// Resolve preset
const preset = resolvePreset(buildConfig.preset || pkg.unbuild?.preset || pkg.build?.preset || inputConfig.preset || 'auto', rootDir)
// Merge options
const options = defu(buildConfig, pkg.unbuild || pkg.build, inputConfig, preset, <BuildOptions>{
rootDir,
entries: [],
clean: true,
declaration: false,
outDir: 'dist',
stub,
externals: [
...Module.builtinModules,
...Module.builtinModules.map(m => 'node:' + m)
],
dependencies: [],
devDependencies: [],
peerDependencies: [],
alias: {},
replace: {},
rollup: {
emitCJS: false,
cjsBridge: false,
inlineDependencies: false,
// Plugins
replace: {
preventAssignment: true
},
alias: {},
resolve: {
preferBuiltins: true
},
json: {
preferConst: true
},
commonjs: {
ignoreTryCatch: true
},
esbuild: { target: 'es2020' },
dts: {
// https://github.com/Swatinem/rollup-plugin-dts/issues/143
compilerOptions: { preserveSymlinks: false },
respectExternal: true
}
}
}) as BuildOptions
// Resolve dirs relative to rootDir
options.outDir = resolve(options.rootDir, options.outDir)
// Build context
const ctx: BuildContext = {
options,
pkg,
buildEntries: [],
usedImports: new Set(),
hooks: createHooks()
}
// Register hooks
if (preset.hooks) {
ctx.hooks.addHooks(preset.hooks)
}
if (inputConfig.hooks) {
ctx.hooks.addHooks(inputConfig.hooks)
}
if (buildConfig.hooks) {
ctx.hooks.addHooks(buildConfig.hooks)
}
// Allow prepare and extending context
await ctx.hooks.callHook('build:prepare', ctx)
// Normalize entries
options.entries = options.entries.map(entry =>
typeof entry === 'string' ? { input: entry } : entry
)
for (const entry of options.entries) {
if (typeof entry.name !== 'string') {
entry.name = basename(entry.input)
}
if (!entry.input) {
throw new Error('Missing entry input: ' + dumpObject(entry))
}
if (!entry.builder) {
entry.builder = entry.input.endsWith('/') ? 'mkdist' : 'rollup'
}
if (options.declaration !== undefined && entry.declaration === undefined) {
entry.declaration = options.declaration
}
entry.input = resolve(options.rootDir, entry.input)
entry.outDir = resolve(options.rootDir, entry.outDir || options.outDir)
}
// Infer dependencies from pkg
options.dependencies = Object.keys(pkg.dependencies || {})
options.peerDependencies = Object.keys(pkg.peerDependencies || {})
options.devDependencies = Object.keys(pkg.devDependencies || {})
// Add all dependencies as externals
options.externals.push(...options.dependencies, ...options.peerDependencies)
// Call build:before
await ctx.hooks.callHook('build:before', ctx)
// Start info
consola.info(chalk.cyan(`${options.stub ? 'Stubbing' : 'Building'} ${pkg.name}`))
if (process.env.DEBUG) {
consola.info(`${chalk.bold('Root dir:')} ${options.rootDir}
${chalk.bold('Entries:')}
${options.entries.map(entry => ' ' + dumpObject(entry)).join('\n ')}
`)
}
// Clean dist dirs
if (options.clean) {
for (const dir of new Set(options.entries.map(e => e.outDir).sort())) {
await rmdir(dir!)
await mkdirp(dir!)
}
}
// Try to selflink
// if (ctx.stub && ctx.pkg.name) {
// const nodemodulesDir = resolve(ctx.rootDir, 'node_modules', ctx.pkg.name)
// await symlink(resolve(ctx.rootDir), nodemodulesDir).catch(() => {})
// }
// untyped
await typesBuild(ctx)
// mkdist
await mkdistBuild(ctx)
// rollup
await rollupBuild(ctx)
// Skip rest for stub
if (options.stub) {
await ctx.hooks.callHook('build:done', ctx)
return
}
// Done info
consola.success(chalk.green('Build succeeded for ' + pkg.name))
for (const entry of ctx.buildEntries) {
consola.log(` ${chalk.bold(entry.path)} (` + [
entry.bytes && `size: ${chalk.cyan(prettyBytes(entry.bytes))}`,
entry.exports && `exports: ${chalk.gray(entry.exports.join(', '))}`,
entry.chunks && `chunks: ${chalk.gray(entry.chunks.join(', '))}`
].filter(Boolean).join(', ') + ')')
}
// Validate
validateDependencies(ctx)
validatePackage(pkg, rootDir)
// Call build:done
await ctx.hooks.callHook('build:done', ctx)
consola.log('')
}