-
Notifications
You must be signed in to change notification settings - Fork 2
/
build.ts
84 lines (73 loc) · 2.19 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
/*
This script was taken from hono https://github.com/honojs/hono/blob/main/build.ts
Everything below is theres
*/
/*
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 { build } from 'esbuild'
import type { Plugin, PluginBuild, BuildOptions } from 'esbuild'
import glob from 'glob'
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)) {
if (args.path.endsWith('/')) {
importPath = `${args.path}index${extension}`
} else {
importPath = `${args.path}/index${extension}`
}
}
}
return { path: importPath, external: true }
}
})
},
})
const commonOptions: BuildOptions = {
entryPoints,
logLevel: 'info',
platform: 'node',
tsconfig: 'tsconfig.json',
}
const cjsBuild = () =>
build({
...commonOptions,
outbase: './src',
outdir: './dist/cjs',
format: 'cjs',
tsconfig: 'tsconfig.cjs.json',
})
const esmBuild = () =>
build({
...commonOptions,
bundle: true,
outbase: './src',
outdir: './dist',
format: 'esm',
plugins: [addExtension('.js')],
})
Promise.all([esmBuild(), cjsBuild()])
exec(`tsc --emitDeclarationOnly --declaration --project tsconfig.build.json`)