@iopa/router
Version:
Lightweight and fast router for IOPA applications
119 lines (111 loc) • 2.78 kB
JavaScript
import { spawn } from 'child_process'
import fs from 'fs'
import esbuild from 'esbuild'
const { name, dependencies, peerDependencies } = JSON.parse(
fs.readFileSync('./package.json')
)
const label = name.split('/', 2)[name.split('/', 2).length - 1]
const isWatchMode =
process.argv.includes('watch') ||
process.argv.includes('-w') ||
process.argv.includes('--watch')
const tscTypeChecker = spawn(
'npx',
[
'tsc',
'--declaration',
'--emitDeclarationOnly',
'--declarationMap',
'--preserveWatchOutput'
].concat(isWatchMode ? '-w' : []),
{ shell: true }
)
function displayChunk(chunk) {
if (
/^\s*$/.test(chunk) ||
/^\s*[\d.: ]+.{0,5}?Starting compilation in watch mode...\s*$/.test(
chunk.toString()
) ||
/^\s*[\d.: ]+.{0,5}?Starting compilation in watch mode...\s*[\d.: ]+.{0,5}?Found 0 errors. Watching for file changes\s*$/.test(
chunk.toString()
) ||
/^\s*[\d.: ]+.{0,5}?File change detected. Starting incremental compilation...\s*[\d.: ]+.{0,5}?Found 0 errors. Watching for file changes\s*$/.test(
chunk.toString()
) ||
/^\s*[\d.: ]+.{0,5}?File change detected. Starting incremental compilation...\s*$/.test(
chunk.toString()
)
)
return
process.stdout.write(chunk)
}
tscTypeChecker.stdout.on('data', displayChunk)
tscTypeChecker.stderr.on('data', (chunk) => {
process.stderr.write(chunk)
})
tscTypeChecker.on('exit', (code) => {
if (isWatchMode) return
if (code === 0) {
console.log('tsc successful')
return
}
console.error('tsc failed')
process.exit(1)
})
console.log('started tsc')
function watchFeedback(label) {
return (error) => {
if (error)
console.error(
`rebuild ${label} failed${
error.errors.length > 0
? ` with ${error.errors.length} ${
error.errors.length === 1 ? 'error' : 'errors'
}`
: ''
}`
)
else console.log(`rebuild ${label} done`)
}
}
const external = [
'node:*',
'async_hooks',
'stream/*',
'stream',
'zlib',
'net',
'tls',
'http',
'perf_hooks',
'util/*',
...Object.keys(dependencies || {}),
...Object.keys(peerDependencies || {})
]
esbuild
.build({
entryPoints: ['src/index.ts'],
outdir: 'dist',
bundle: true,
format: 'esm',
sourcemap: 'external',
target: 'node16',
mainFields: ['module', 'main'],
plugins: [],
watch: isWatchMode
? {
onRebuild: (error, result) => {
watchFeedback(label)(error)
}
}
: false,
external
})
.catch((e) => {
console.error(e)
process.exit(1)
})
.then(() => {
console.log(`esbuild ${label} transpiled`)
})
if (isWatchMode) console.log('esbuild started watch')