This repository has been archived by the owner on Dec 23, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
build.ts
98 lines (84 loc) · 2.55 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
89
90
91
92
93
94
95
96
97
98
/*
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 * as fsp from 'fs/promises'
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'],
})
/*
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`)
async function copyFile(source, destination) {
try {
const data = await fsp.readFile(source)
await fsp.writeFile(destination, data)
console.log(`${source} を ${destination} にコピーしました。`)
} catch (error) {
console.error(`ファイルのコピー中にエラーが発生しました: ${error}`)
}
}
const sourcePath = './package.cjs.json'
const distCjsPath = './dist/cjs/package.json'
const distTypesPath = './dist/types/package.json'
copyFile(sourcePath, distCjsPath)
copyFile(sourcePath, distTypesPath)