-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.ts
88 lines (71 loc) · 2.44 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
import { parseArgs } from 'https://deno.land/std@0.220.1/cli/parse_args.ts'
import { dirname, join } from 'https://deno.land/std@0.220.1/path/mod.ts'
import { gzipSync } from 'https://esm.sh/fflate@0.8.2'
import { compile, type CompiledFile } from './compiler/mod.ts'
import { configure } from './config/mod.ts'
if (import.meta.main) {
const flags = parseArgs(Deno.args, { string: ['o'], boolean: ['h', 'q'], alias: { h: 'help' } })
if (flags.h) {
console.error`usage: ./input.ts ./input2.ts # will output the build result to stdout`
console.error`usage: -o dist ./input.ts ./input2.ts # will write the build result to dist`
Deno.exit(1)
}
const urls = flags._.filter(isString)
const config = await configure({ mode: 'prod' })
const bundle = await compile(urls, { config })
for (const entryPoint of bundle.entryPoints) {
await outputFile(entryPoint, flags.q, flags.o)
}
for (const file of bundle.files) {
await outputFile(file, flags.q, flags.o)
}
Deno.exit(0)
}
function isString(u: unknown): u is string {
return typeof u === 'string'
}
async function outputFile(file: CompiledFile, beQuiet: boolean, outputDir?: string): Promise<void> {
if (file.urlPath.endsWith('.map') && !outputDir) {
return
}
const gzip = gzipSync(file.contents)
const relPath = file.urlPath.replace(/^\//, '')
const decoder = new TextDecoder()
if (!beQuiet) {
console.info(relPath)
console.info(`file size: ${formatSize(file.contents.byteLength)}`)
console.info(`gzip size: ${formatSize(gzip.byteLength)}`)
}
if (outputDir) {
const path = join(outputDir, relPath)
await Deno.mkdir(dirname(path), { recursive: true })
await Deno.writeFile(path, file.contents)
if (!beQuiet) {
console.info(`wrote file to: ${path}`)
}
} else {
console.log(decoder.decode(file.contents))
}
console.log('\n')
}
function formatSize(size: number): string {
let finalSize = 0
let postfix = ''
if (size < 1024) {
finalSize = size
postfix = ' bytes'
} else if (size < 1024 * 1024) {
finalSize = size / 1024
postfix = 'kb'
} else if (size < 1024 * 1024 * 1024) {
finalSize = size / 1024 / 1024
postfix = 'mb'
} else if (size < 1024 * 1024 * 1024 * 1024) {
finalSize = size / 1024 / 1024 / 1024
postfix = 'gb'
}
let sizeString = finalSize.toFixed(2)
sizeString = sizeString.replace(/0+$/, '')
sizeString = sizeString.replace(/\.$/, '')
return `${sizeString}${postfix}`
}