#!/usr/bin/env node process.on('unhandledRejection', (err: unknown) => { throw err; }); import { spawn, ChildProcess } from 'child_process'; const fs: typeof import('fs') = require('fs'); const chokidar: typeof import('chokidar') = require('chokidar'); const path: typeof import('path') = require('path'); const chalk: typeof import('chalk') = require('chalk'); // Clear console helper function clearConsole(): void { process.stdout.write('\x1B[2J\x1B[0f'); } const args = process.argv.slice(2); const scriptIndex = args.findIndex(x => ['start', 'build'].includes(x)); const script: string | undefined = scriptIndex === -1 ? args[0] : args[scriptIndex]; const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : []; function run(script: string, openBrowser = true): ChildProcess { // 使用 __dirname 来构建正确的路径 // 编译后的文件在 lib/bin/ 目录下,scripts 在 lib/scripts/ 目录下 const scriptPath = require.resolve(path.join(__dirname, '../scripts/' + script)); return spawn(process.execPath, nodeArgs.concat(scriptPath).concat(args), { stdio: 'inherit', env: { ...process.env, NODE_ENV: script === 'start' ? 'development' : process.env.NODE_ENV || 'production', /** 是否自动打开浏览器,配置文件改动重新编译时为否 */ OPEN_BROWSER: String(openBrowser), }, }); } // 支持监听 .ts 配置文件 const resolveConfigPath = (): string | null => { const tsPath = path.resolve(process.cwd(), 'deppon.config.ts'); if (fs.existsSync(tsPath)) { return tsPath; } return null; }; const configPath = resolveConfigPath(); if (['build', 'start'].includes(script || '')) { let subScript = run(script!); if (script === 'start' && configPath) { chokidar.watch(configPath).on('change', () => { clearConsole(); console.log(chalk.cyan('配置文件改动,重新编译中...')); subScript.kill(); subScript = run(script, false); }); } } else { if (!script) { console.log(`请提供有效的操作指令: start, build`); } else { console.log('无效脚本 "' + script + '".'); } }