forked from honojs/hono
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.ts
80 lines (69 loc) · 2.03 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
/*
This script is heavily inspired by `built.ts` used in @kaze-style/react.
https://github.com/taishinaritomi/kaze-style/blob/main/scripts/build.ts
MIT License
Copyright (c) 2022 Taishi Naritomi
*/
import { exec } from 'child_process'
import fs from 'fs'
import path from 'path'
import arg from 'arg'
import { build } from 'esbuild'
import type { Plugin, PluginBuild, BuildOptions } from 'esbuild'
import glob from 'glob'
const args = arg({
'--watch': Boolean,
})
const isWatch = args['--watch'] || false
const entryPoints = glob.sync('./src/**/*.ts', {
ignore: ['./src/**/*.test.ts', './src/mod.ts', './src/middleware.ts', './src/deno/**/*.ts'],
})
/*
This plugin is inspired by the following.
https://github.com/evanw/esbuild/issues/622#issuecomment-769462611
*/
const addExtension = (extension: string = '.js', fileExtension: string = '.ts'): Plugin => ({
name: 'add-extension',
setup(build: PluginBuild) {
build.onResolve({ filter: /.*/ }, (args) => {
if (args.importer) {
const p = path.join(args.resolveDir, args.path)
let tsPath = `${p}${fileExtension}`
let importPath = ''
if (fs.existsSync(tsPath)) {
importPath = args.path + extension
} else {
tsPath = path.join(args.resolveDir, args.path, `index${fileExtension}`)
if (fs.existsSync(tsPath)) {
importPath = `${args.path}/index${extension}`
}
}
return { path: importPath, external: true }
}
})
},
})
const commonOptions: BuildOptions = {
watch: isWatch,
entryPoints,
logLevel: 'info',
platform: 'node',
}
const cjsBuild = () =>
build({
...commonOptions,
outbase: './src',
outdir: './dist/cjs',
format: 'cjs',
})
const esmBuild = () =>
build({
...commonOptions,
bundle: true,
outbase: './src',
outdir: './dist',
format: 'esm',
plugins: [addExtension('.js')],
})
Promise.all([esmBuild(), cjsBuild()])
exec(`tsc ${isWatch ? '-w' : ''} --emitDeclarationOnly --declaration --project tsconfig.build.json`)