-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
rollup.ts
255 lines (233 loc) · 7.42 KB
/
rollup.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import { parentPort } from 'node:worker_threads'
import path from 'node:path'
import ts from 'typescript'
import jsonPlugin from '@rollup/plugin-json'
import resolveFrom from 'resolve-from'
import { handleError } from './errors'
import { defaultOutExtension, removeFiles, toObjectEntry } from './utils'
import { type TsResolveOptions, tsResolvePlugin } from './rollup/ts-resolve'
import { createLogger, setSilent } from './log'
import { getProductionDeps, loadPkg } from './load'
import { reportSize } from './lib/report-size'
import type { NormalizedOptions } from './'
import type { InputOptions, OutputOptions, Plugin } from 'rollup'
const logger = createLogger()
const parseCompilerOptions = (compilerOptions?: any) => {
if (!compilerOptions) return {}
const { options } = ts.parseJsonConfigFileContent(
{ compilerOptions },
ts.sys,
'./',
)
return options
}
// Use `require` to esbuild use the cjs build of rollup-plugin-dts
// the mjs build of rollup-plugin-dts uses `import.meta.url` which makes Node throws syntax error
// since tsup is published as a commonjs module for now
const dtsPlugin: typeof import('rollup-plugin-dts') = require('rollup-plugin-dts')
type RollupConfig = {
inputConfig: InputOptions
outputConfig: OutputOptions[]
}
const getRollupConfig = async (
options: NormalizedOptions,
): Promise<RollupConfig> => {
setSilent(options.silent)
const compilerOptions = parseCompilerOptions(options.dts?.compilerOptions)
const dtsOptions = options.dts || {}
dtsOptions.entry = dtsOptions.entry || options.entry
if (Array.isArray(dtsOptions.entry) && dtsOptions.entry.length > 1) {
dtsOptions.entry = toObjectEntry(dtsOptions.entry)
}
let tsResolveOptions: TsResolveOptions | undefined
if (dtsOptions.resolve) {
tsResolveOptions = {}
// Only resolve specific types when `dts.resolve` is an array
if (Array.isArray(dtsOptions.resolve)) {
tsResolveOptions.resolveOnly = dtsOptions.resolve
}
// `paths` should be handled by rollup-plugin-dts
if (compilerOptions.paths) {
const res = Object.keys(compilerOptions.paths).map(
(p) => new RegExp(`^${p.replace('*', '.+')}$`),
)
tsResolveOptions.ignore = (source) => {
return res.some((re) => re.test(source))
}
}
}
const pkg = await loadPkg(process.cwd())
const deps = await getProductionDeps(process.cwd())
const tsupCleanPlugin: Plugin = {
name: 'tsup:clean',
async buildStart() {
if (options.clean) {
await removeFiles(['**/*.d.{ts,mts,cts}'], options.outDir)
}
},
}
const ignoreFiles: Plugin = {
name: 'tsup:ignore-files',
load(id) {
if (!/\.(js|cjs|mjs|jsx|ts|tsx|mts|json)$/.test(id)) {
return ''
}
},
}
const fixCjsExport: Plugin = {
name: 'tsup:fix-cjs-export',
renderChunk(code, info) {
if (
info.type !== 'chunk' ||
!/\.(ts|cts)$/.test(info.fileName) ||
!info.isEntry ||
info.exports?.length !== 1 ||
info.exports[0] !== 'default'
)
return
return code.replace(
/(?<=(?<=[;}]|^)\s*export\s*){\s*([\w$]+)\s*as\s+default\s*}/,
`= $1`,
)
},
}
return {
inputConfig: {
input: dtsOptions.entry,
onwarn(warning, handler) {
if (
warning.code === 'UNRESOLVED_IMPORT' ||
warning.code === 'CIRCULAR_DEPENDENCY' ||
warning.code === 'EMPTY_BUNDLE'
) {
return
}
return handler(warning)
},
plugins: [
tsupCleanPlugin,
tsResolveOptions && tsResolvePlugin(tsResolveOptions),
jsonPlugin(),
ignoreFiles,
dtsPlugin.default({
tsconfig: options.tsconfig,
compilerOptions: {
...compilerOptions,
baseUrl: compilerOptions.baseUrl || '.',
// Ensure ".d.ts" modules are generated
declaration: true,
// Skip ".js" generation
noEmit: false,
emitDeclarationOnly: true,
// Skip code generation when error occurs
noEmitOnError: true,
// Avoid extra work
checkJs: false,
declarationMap: false,
skipLibCheck: true,
preserveSymlinks: false,
// Ensure we can parse the latest code
target: ts.ScriptTarget.ESNext,
},
}),
].filter(Boolean),
external: [
// Exclude dependencies, e.g. `lodash`, `lodash/get`
...deps.map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`)),
...(options.external || []),
],
},
outputConfig: options.format.map((format): OutputOptions => {
const outputExtension =
options.outExtension?.({ format, options, pkgType: pkg.type }).dts ||
defaultOutExtension({ format, pkgType: pkg.type }).dts
return {
dir: options.outDir || 'dist',
format: 'esm',
exports: 'named',
banner: dtsOptions.banner,
footer: dtsOptions.footer,
entryFileNames: `[name]${outputExtension}`,
chunkFileNames: `[name]-[hash]${outputExtension}`,
plugins: [
format === 'cjs' && options.cjsInterop && fixCjsExport,
].filter(Boolean),
}
}),
}
}
async function runRollup(options: RollupConfig) {
const { rollup } = await import('rollup')
try {
const start = Date.now()
const getDuration = () => {
return `${Math.floor(Date.now() - start)}ms`
}
logger.info('dts', 'Build start')
const bundle = await rollup(options.inputConfig)
const results = await Promise.all(options.outputConfig.map(bundle.write))
const outputs = results.flatMap((result) => result.output)
logger.success('dts', `⚡️ Build success in ${getDuration()}`)
reportSize(
logger,
'dts',
outputs.reduce((res, info) => {
const name = path.relative(
process.cwd(),
path.join(options.outputConfig[0].dir || '.', info.fileName),
)
return {
...res,
[name]: info.type === 'chunk' ? info.code.length : info.source.length,
}
}, {}),
)
} catch (error) {
handleError(error)
logger.error('dts', 'Build error')
}
}
async function watchRollup(options: {
inputConfig: InputOptions
outputConfig: OutputOptions[]
}) {
const { watch } = await import('rollup')
watch({
...options.inputConfig,
plugins: options.inputConfig.plugins,
output: options.outputConfig,
}).on('event', (event) => {
if (event.code === 'START') {
logger.info('dts', 'Build start')
} else if (event.code === 'BUNDLE_END') {
logger.success('dts', `⚡️ Build success in ${event.duration}ms`)
parentPort?.postMessage('success')
} else if (event.code === 'ERROR') {
logger.error('dts', 'Build failed')
handleError(event.error)
}
})
}
const startRollup = async (options: NormalizedOptions) => {
const config = await getRollupConfig(options)
if (options.watch) {
watchRollup(config)
} else {
try {
await runRollup(config)
parentPort?.postMessage('success')
} catch {
parentPort?.postMessage('error')
}
}
}
parentPort?.on('message', (data) => {
logger.setName(data.configName)
const hasTypescript = resolveFrom.silent(process.cwd(), 'typescript')
if (!hasTypescript) {
logger.error('dts', `You need to install "typescript" in your project`)
parentPort?.postMessage('error')
return
}
startRollup(data.options)
})