reorganized main file

This commit is contained in:
2022-06-08 16:46:44 -05:00
parent 3fdb3ad110
commit 74904d1c0f
8 changed files with 240 additions and 123 deletions

71
src/build.ts Normal file
View File

@@ -0,0 +1,71 @@
import { build, BuildFailure } from 'esbuild'
import { existsSync, readFileSync, writeFileSync, unlinkSync } from 'fs'
import { DistPath, ScriptPath } from './paths'
import { UserScriptMetaFull } from './types'
import readMeta from './readmeta'
export default async function (
name: string,
watchCallback:
| ((meta: UserScriptMetaFull, error: string | null) => void)
| false = false
): Promise<[UserScriptMetaFull, string | null]> {
//read meta file
let [metaJson, metaString] = readMeta(name)
let outPath = DistPath(name)
let error: string | null = null
try {
await build({
entryPoints: [ScriptPath(name).main],
outfile: outPath,
target: 'esnext',
platform: 'node',
format: 'esm',
bundle: true,
minify: false,
watch: !watchCallback
? false
: {
onRebuild(err, result) {
if (err) {
console.error(name, err)
let error = (err as BuildFailure).message
watchCallback(metaJson, error)
} else {
console.log('watch build succeeded:', result)
}
},
},
define: {
UserScriptName: `'${metaJson.name}'`,
UserScriptNamespace: `'${metaJson.namespace}'`,
UserScriptVersion: `'${metaJson.version}'`,
UserScriptDownloadURL: `'${metaJson.downloadURL}'`,
UserScriptSupportURL: `'${metaJson.supportURL}'`,
UserScriptHomepageURL: `'${metaJson.homepageURL}'`,
},
})
} catch (err) {
console.error(name, err)
error = (err as BuildFailure).message
}
//add UserScript header
if (existsSync(outPath)) {
if (!error) {
let content = readFileSync(outPath).toString()
writeFileSync(outPath, metaString + content)
} else {
unlinkSync(outPath)
}
}
return [metaJson, error]
}