/
build.spec.ts
557 lines (494 loc) · 15.5 KB
/
build.spec.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import colors from 'picocolors'
import type { Logger } from 'vite'
import { describe, expect, test, vi } from 'vitest'
import type { OutputChunk, OutputOptions, RollupOutput } from 'rollup'
import type { LibraryFormats, LibraryOptions } from '../build'
import { build, resolveBuildOutputs, resolveLibFilename } from '../build'
import { createLogger } from '../logger'
const __dirname = resolve(fileURLToPath(import.meta.url), '..')
type FormatsToFileNames = [LibraryFormats, string][]
describe('build', () => {
test('file hash should change when css changes for dynamic entries', async () => {
const buildProject = async (cssColor: string) => {
return (await build({
root: resolve(__dirname, 'packages/build-project'),
logLevel: 'silent',
build: {
write: false,
},
plugins: [
{
name: 'test',
resolveId(id) {
if (
id === 'entry.js' ||
id === 'subentry.js' ||
id === 'foo.css'
) {
return '\0' + id
}
},
load(id) {
if (id === '\0entry.js') {
return `window.addEventListener('click', () => { import('subentry.js') });`
}
if (id === '\0subentry.js') {
return `import 'foo.css'`
}
if (id === '\0foo.css') {
return `.foo { color: ${cssColor} }`
}
},
},
],
})) as RollupOutput
}
const result = await Promise.all([
buildProject('red'),
buildProject('blue'),
])
assertOutputHashContentChange(result[0], result[1])
})
test('file hash should change when pure css chunk changes', async () => {
const buildProject = async (cssColor: string) => {
return (await build({
root: resolve(__dirname, 'packages/build-project'),
logLevel: 'silent',
build: {
write: false,
},
plugins: [
{
name: 'test',
resolveId(id) {
if (
id === 'entry.js' ||
id === 'foo.js' ||
id === 'bar.js' ||
id === 'baz.js' ||
id === 'foo.css' ||
id === 'bar.css' ||
id === 'baz.css'
) {
return '\0' + id
}
},
load(id) {
if (id === '\0entry.js') {
return `
window.addEventListener('click', () => { import('foo.js') });
window.addEventListener('click', () => { import('bar.js') });`
}
if (id === '\0foo.js') return `import 'foo.css'; import 'baz.js'`
if (id === '\0bar.js') return `import 'bar.css'; import 'baz.js'`
if (id === '\0baz.js') return `import 'baz.css'`
if (id === '\0foo.css') return `.foo { color: red }`
if (id === '\0bar.css') return `.foo { color: green }`
if (id === '\0baz.css') return `.foo { color: ${cssColor} }`
},
},
],
})) as RollupOutput
}
const result = await Promise.all([
buildProject('yellow'),
buildProject('blue'),
])
assertOutputHashContentChange(result[0], result[1])
})
})
const baseLibOptions: LibraryOptions = {
fileName: 'my-lib',
entry: 'mylib.js',
}
describe('resolveBuildOutputs', () => {
test('resolves outputs correctly', () => {
const logger = createLogger()
const libOptions: LibraryOptions = { ...baseLibOptions }
const outputs: OutputOptions[] = [{ format: 'es' }]
const resolvedOutputs = resolveBuildOutputs(outputs, libOptions, logger)
expect(resolvedOutputs).toEqual([
{
format: 'es',
},
])
})
test('resolves outputs from lib options', () => {
const logger = createLogger()
const libOptions: LibraryOptions = { ...baseLibOptions, name: 'lib' }
const resolvedOutputs = resolveBuildOutputs(void 0, libOptions, logger)
expect(resolvedOutputs).toEqual([
{
format: 'es',
},
{
format: 'umd',
},
])
})
test('does not change outputs when lib options are missing', () => {
const logger = createLogger()
const outputs: OutputOptions[] = [{ format: 'es' }]
const resolvedOutputs = resolveBuildOutputs(outputs, false, logger)
expect(resolvedOutputs).toEqual(outputs)
})
test('logs a warning when outputs is an array and formats are specified', () => {
const logger = createLogger()
const loggerSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
const libOptions: LibraryOptions = {
...baseLibOptions,
formats: ['iife'],
}
const outputs: OutputOptions[] = [{ format: 'es' }]
resolveBuildOutputs(outputs, libOptions, logger)
expect(loggerSpy).toHaveBeenCalledWith(
expect.stringContaining('"build.lib.formats" will be ignored because'),
)
})
test('throws an error when lib.name is missing on iife format', () => {
const logger = createLogger()
const libOptions: LibraryOptions = {
...baseLibOptions,
formats: ['iife'],
}
const resolveBuild = () => resolveBuildOutputs(void 0, libOptions, logger)
expect(resolveBuild).toThrowError(/Option "build\.lib\.name" is required/)
})
test('throws an error when lib.name is missing on umd format', () => {
const logger = createLogger()
const libOptions: LibraryOptions = { ...baseLibOptions, formats: ['umd'] }
const resolveBuild = () => resolveBuildOutputs(void 0, libOptions, logger)
expect(resolveBuild).toThrowError(/Option "build\.lib\.name" is required/)
})
test('throws an error when output.name is missing on iife format', () => {
const logger = createLogger()
const libOptions: LibraryOptions = { ...baseLibOptions }
const outputs: OutputOptions[] = [{ format: 'iife' }]
const resolveBuild = () => resolveBuildOutputs(outputs, libOptions, logger)
expect(resolveBuild).toThrowError(
/Entries in "build\.rollupOptions\.output" must specify "name"/,
)
})
test('throws an error when output.name is missing on umd format', () => {
const logger = createLogger()
const libOptions: LibraryOptions = { ...baseLibOptions }
const outputs: OutputOptions[] = [{ format: 'umd' }]
const resolveBuild = () => resolveBuildOutputs(outputs, libOptions, logger)
expect(resolveBuild).toThrowError(
/Entries in "build\.rollupOptions\.output" must specify "name"/,
)
})
})
describe('resolveLibFilename', () => {
test('custom filename function', () => {
const filename = resolveLibFilename(
{
fileName: (format) => `custom-filename-function.${format}.js`,
entry: 'mylib.js',
},
'es',
'myLib',
resolve(__dirname, 'packages/name'),
)
expect(filename).toBe('custom-filename-function.es.js')
})
test('custom filename string', () => {
const filename = resolveLibFilename(
{
fileName: 'custom-filename',
entry: 'mylib.js',
},
'es',
'myLib',
resolve(__dirname, 'packages/name'),
)
expect(filename).toBe('custom-filename.mjs')
})
test('package name as filename', () => {
const filename = resolveLibFilename(
{
entry: 'mylib.js',
},
'es',
'myLib',
resolve(__dirname, 'packages/name'),
)
expect(filename).toBe('mylib.mjs')
})
test('custom filename and no package name', () => {
const filename = resolveLibFilename(
{
fileName: 'custom-filename',
entry: 'mylib.js',
},
'es',
'myLib',
resolve(__dirname, 'packages/noname'),
)
expect(filename).toBe('custom-filename.mjs')
})
test('missing filename', () => {
expect(() => {
resolveLibFilename(
{
entry: 'mylib.js',
},
'es',
'myLib',
resolve(__dirname, 'packages/noname'),
)
}).toThrow()
})
test('commonjs package extensions', () => {
const formatsToFilenames: FormatsToFileNames = [
['es', 'my-lib.mjs'],
['umd', 'my-lib.umd.js'],
['cjs', 'my-lib.js'],
['iife', 'my-lib.iife.js'],
]
for (const [format, expectedFilename] of formatsToFilenames) {
const filename = resolveLibFilename(
baseLibOptions,
format,
'myLib',
resolve(__dirname, 'packages/noname'),
)
expect(filename).toBe(expectedFilename)
}
})
test('module package extensions', () => {
const formatsToFilenames: FormatsToFileNames = [
['es', 'my-lib.js'],
['umd', 'my-lib.umd.cjs'],
['cjs', 'my-lib.cjs'],
['iife', 'my-lib.iife.js'],
]
for (const [format, expectedFilename] of formatsToFilenames) {
const filename = resolveLibFilename(
baseLibOptions,
format,
'myLib',
resolve(__dirname, 'packages/module'),
)
expect(expectedFilename).toBe(filename)
}
})
test('multiple entries with aliases', () => {
const libOptions: LibraryOptions = {
entry: {
entryA: 'entryA.js',
entryB: 'entryB.js',
},
}
const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
resolveLibFilename(
libOptions,
'es',
entryAlias,
resolve(__dirname, 'packages/name'),
),
)
expect(fileName1).toBe('entryA.mjs')
expect(fileName2).toBe('entryB.mjs')
})
test('multiple entries with aliases: custom filename function', () => {
const libOptions: LibraryOptions = {
entry: {
entryA: 'entryA.js',
entryB: 'entryB.js',
},
fileName: (format, entryAlias) =>
`custom-filename-function.${entryAlias}.${format}.js`,
}
const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
resolveLibFilename(
libOptions,
'es',
entryAlias,
resolve(__dirname, 'packages/name'),
),
)
expect(fileName1).toBe('custom-filename-function.entryA.es.js')
expect(fileName2).toBe('custom-filename-function.entryB.es.js')
})
test('multiple entries with aliases: custom filename string', () => {
const libOptions: LibraryOptions = {
entry: {
entryA: 'entryA.js',
entryB: 'entryB.js',
},
fileName: 'custom-filename',
}
const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
resolveLibFilename(
libOptions,
'es',
entryAlias,
resolve(__dirname, 'packages/name'),
),
)
expect(fileName1).toBe('custom-filename.mjs')
expect(fileName2).toBe('custom-filename.mjs')
})
test('multiple entries as array', () => {
const libOptions: LibraryOptions = {
entry: ['entryA.js', 'entryB.js'],
}
const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
resolveLibFilename(
libOptions,
'es',
entryAlias,
resolve(__dirname, 'packages/name'),
),
)
expect(fileName1).toBe('entryA.mjs')
expect(fileName2).toBe('entryB.mjs')
})
test('multiple entries as array: custom filename function', () => {
const libOptions: LibraryOptions = {
entry: ['entryA.js', 'entryB.js'],
fileName: (format, entryAlias) =>
`custom-filename-function.${entryAlias}.${format}.js`,
}
const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
resolveLibFilename(
libOptions,
'es',
entryAlias,
resolve(__dirname, 'packages/name'),
),
)
expect(fileName1).toBe('custom-filename-function.entryA.es.js')
expect(fileName2).toBe('custom-filename-function.entryB.es.js')
})
test('multiple entries as array: custom filename string', () => {
const libOptions: LibraryOptions = {
entry: ['entryA.js', 'entryB.js'],
fileName: 'custom-filename',
}
const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
resolveLibFilename(
libOptions,
'es',
entryAlias,
resolve(__dirname, 'packages/name'),
),
)
expect(fileName1).toBe('custom-filename.mjs')
expect(fileName2).toBe('custom-filename.mjs')
})
})
describe('resolveBuildOutputs', () => {
test('default format: one entry', () => {
const libOptions: LibraryOptions = {
entry: 'entryA.js',
name: 'entryA',
}
expect(resolveBuildOutputs(undefined, libOptions, {} as Logger)).toEqual([
{ format: 'es' },
{ format: 'umd' },
])
expect(
resolveBuildOutputs({ name: 'A' }, libOptions, {} as Logger),
).toEqual([
{ format: 'es', name: 'A' },
{ format: 'umd', name: 'A' },
])
expect(
resolveBuildOutputs([{ name: 'A' }], libOptions, {} as Logger),
).toEqual([{ name: 'A' }])
})
test('default format: multiple entries', () => {
const libOptions: LibraryOptions = {
entry: ['entryA.js', 'entryB.js'],
}
expect(resolveBuildOutputs(undefined, libOptions, {} as Logger)).toEqual([
{ format: 'es' },
{ format: 'cjs' },
])
expect(
resolveBuildOutputs({ name: 'A' }, libOptions, {} as Logger),
).toEqual([
{ format: 'es', name: 'A' },
{ format: 'cjs', name: 'A' },
])
expect(
resolveBuildOutputs([{ name: 'A' }], libOptions, {} as Logger),
).toEqual([{ name: 'A' }])
})
test('umd or iife: should not support multiple entries', () => {
;['umd', 'iife'].forEach((format) => {
expect(() =>
resolveBuildOutputs(
undefined,
{
entry: ['entryA.js', 'entryB.js'],
formats: [format as LibraryFormats],
},
{} as Logger,
),
).toThrow(
`Multiple entry points are not supported when output formats include "umd" or "iife".`,
)
})
})
test('umd or iife: should define build.lib.name', () => {
;['umd', 'iife'].forEach((format) => {
expect(() =>
resolveBuildOutputs(
undefined,
{
entry: 'entryA.js',
formats: [format as LibraryFormats],
},
{} as Logger,
),
).toThrow(
`Option "build.lib.name" is required when output formats include "umd" or "iife".`,
)
})
})
test('array outputs: should ignore build.lib.formats', () => {
const log = { warn: vi.fn() } as unknown as Logger
expect(
resolveBuildOutputs(
[{ name: 'A' }],
{
entry: 'entryA.js',
formats: ['es'],
},
log,
),
).toEqual([{ name: 'A' }])
expect(log.warn).toHaveBeenLastCalledWith(
colors.yellow(
`"build.lib.formats" will be ignored because "build.rollupOptions.output" is already an array format.`,
),
)
})
})
/**
* for each chunks in output1, if there's a chunk in output2 with the same fileName,
* ensure that the chunk code is the same. if not, the chunk hash should have changed.
*/
function assertOutputHashContentChange(
output1: RollupOutput,
output2: RollupOutput,
) {
for (const chunk of output1.output) {
if (chunk.type === 'chunk') {
const chunk2 = output2.output.find(
(c) => c.type === 'chunk' && c.fileName === chunk.fileName,
) as OutputChunk | undefined
if (chunk2) {
expect(
chunk.code,
`the ${chunk.fileName} chunk has the same hash but different contents between builds`,
).toEqual(chunk2.code)
}
}
}
}