|
| 1 | +const fs = require('fs') |
| 2 | +const esbuild = require('esbuild') |
| 3 | +const path = require('path') |
| 4 | + |
| 5 | +// Note: This was adopted from the https://github.com/markwylde/workerbox/blob/master/build.js |
| 6 | +console.log('Building workerbox...') |
| 7 | + |
| 8 | +const DEBUG = process.env.DEBUG === 'true' |
| 9 | +if (DEBUG) console.log('Minification off.') |
| 10 | + |
| 11 | +async function writeFileWithDirs(filePath, data) { |
| 12 | + // Extract the directory path from the file path |
| 13 | + const dir = path.dirname(filePath) |
| 14 | + |
| 15 | + // Ensure the directory exists |
| 16 | + await fs.promises.mkdir(dir, { recursive: true }) |
| 17 | + |
| 18 | + // Write the file |
| 19 | + await fs.promises.writeFile(filePath, data, 'utf8') |
| 20 | +} |
| 21 | + |
| 22 | +async function build() { |
| 23 | + console.log(new Date(), 'rebuilding...') |
| 24 | + |
| 25 | + // clean up dist folder |
| 26 | + await fs.promises.rm('./src/lib/workerbox/dist', { |
| 27 | + recursive: true, |
| 28 | + force: true, |
| 29 | + }) |
| 30 | + |
| 31 | + await esbuild.build({ |
| 32 | + entryPoints: ['./src/lib/workerbox/worker.ts'], |
| 33 | + bundle: true, |
| 34 | + outfile: './src/lib/workerbox/dist/worker.js', |
| 35 | + minify: !DEBUG, |
| 36 | + }) |
| 37 | + |
| 38 | + const jsData = await fs.promises.readFile( |
| 39 | + './src/lib/workerbox/dist/worker.js', |
| 40 | + 'utf8' |
| 41 | + ) |
| 42 | + |
| 43 | + const TEMPLATE_PLACEHOLDER = `{{WORKERSCRIPT}}` |
| 44 | + const htmlData = ( |
| 45 | + await fs.promises.readFile('./src/lib/workerbox/worker.html', 'utf8') |
| 46 | + ).replace(TEMPLATE_PLACEHOLDER, jsData) |
| 47 | + |
| 48 | + await writeFileWithDirs('./src/lib/workerbox/dist/worker.html', htmlData) |
| 49 | + await writeFileWithDirs( |
| 50 | + './src/lib/workerbox/worker.generated.ts', |
| 51 | + [ |
| 52 | + '/* eslint-disable */', |
| 53 | + `// built from /dist/worker.html`, |
| 54 | + `export default atob('${Buffer.from(htmlData).toString('base64')}');`, |
| 55 | + ].join('\n') |
| 56 | + ) |
| 57 | +} |
| 58 | + |
| 59 | +build() |
| 60 | + .then(() => console.log('Build successful')) |
| 61 | + .catch((err) => { |
| 62 | + console.error(err) |
| 63 | + process.exit(1) |
| 64 | + }) |
0 commit comments