Files
work-ts/gulpfile.js
2025-01-21 12:09:37 +08:00

86 lines
2.4 KiB
JavaScript

import { readdir } from 'fs/promises';
import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';
import * as gulp from 'gulp';
import { rm } from 'fs/promises';
// Get the current file's directory
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Define input and output directories
const SRC_DIR = path.join(__dirname, 'src');
const BIN_DIR = path.join(SRC_DIR, 'bin');
const DIST_DIR = path.join(__dirname, 'dist');
// Function to bundle a single file using esbuild
async function buildFile(entryFile) {
const outputFile = path.join(
DIST_DIR,
path.basename(entryFile).replace(/\.ts$/, '.mjs')
);
console.log(`Building: ${entryFile}${outputFile}`);
// Define the esbuild command and arguments
const command = 'esbuild';
const args = [
entryFile,
'--bundle',
'--platform=node',
'--format=esm',
'--minify',
'--loader:.cfg=text',
'--loader:.ini=text',
'--outfile=' + outputFile,
];
// Execute the esbuild command as a child process
return new Promise((resolve, reject) => {
const child = spawn(command, args, { stdio: 'inherit' });
child.on('close', code => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Build failed for ${entryFile} with exit code ${code}`));
}
});
});
}
// Get all files in the src/bin directory
async function getEntryFiles() {
const files = await readdir(BIN_DIR);
return files.map(file => path.join(BIN_DIR, file));
}
// Build all entry files
async function buildAll() {
const entryFiles = await getEntryFiles();
for (const entry of entryFiles) {
await buildFile(entry);
}
}
// Clean the output directory
async function clean() {
try {
console.log(`Cleaning dist directory: ${DIST_DIR}`);
await rm(DIST_DIR, { recursive: true, force: true });
} catch (err) {
console.error('Error cleaning dist directory:', err.message);
}
}
const task = gulp.series(clean, buildAll);
// Watch for file changes and rebuild
export async function watch() {
await task();
console.log('Watching for changes...');
await gulp.watch(SRC_DIR + '/**/*', task);
}
// Export tasks for Gulp
export default task; // Default task