|
| 1 | +import { logPreviewMessage } from './preview/logPreviewMessage.js'; |
| 2 | +import { startDevServer } from '@web/dev-server'; |
| 3 | +import path from 'path'; |
| 4 | +import { existsSync } from 'fs'; |
| 5 | +import { gray, bold } from 'colorette'; |
| 6 | + |
| 7 | +export class RocketPreview { |
| 8 | + /** |
| 9 | + * @param {import('commander').Command} program |
| 10 | + * @param {import('./RocketCli.js').RocketCli} cli |
| 11 | + */ |
| 12 | + async setupCommand(program, cli) { |
| 13 | + this.cli = cli; |
| 14 | + this.active = true; |
| 15 | + |
| 16 | + program |
| 17 | + .command('preview') |
| 18 | + .option('-i, --input-dir <path>', 'path to the folder with the build html files') |
| 19 | + .option('-o, --open', 'automatically open the browser') |
| 20 | + .action(async cliOptions => { |
| 21 | + cli.setOptions(cliOptions); |
| 22 | + cli.activePlugin = this; |
| 23 | + |
| 24 | + await this.preview(); |
| 25 | + }); |
| 26 | + } |
| 27 | + |
| 28 | + async preview() { |
| 29 | + if (!this.cli) { |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + // for typescript as `this.cli.options.outputDir` supports other inputs as well |
| 34 | + // but the cli will normalize it to a string before calling plugins |
| 35 | + if ( |
| 36 | + typeof this.cli.options.inputDir !== 'string' || |
| 37 | + typeof this.cli.options.outputDir !== 'string' |
| 38 | + ) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + const rootIndexHtml = path.join(this.cli.options.outputDir, 'index.html'); |
| 43 | + if (!existsSync(rootIndexHtml)) { |
| 44 | + console.log(`${bold(`👀 Previewing Production Build`)}`); |
| 45 | + console.log(''); |
| 46 | + console.log(` 🛑 No index.html found in the build directory ${gray(`${rootIndexHtml}`)}`); |
| 47 | + console.log(' 🤔 Did you forget to run `rocket build` before?'); |
| 48 | + console.log(''); |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + /** @type {import('@web/dev-server').DevServerConfig} */ |
| 53 | + const config = { |
| 54 | + open: this.cli.options.open, |
| 55 | + rootDir: this.cli.options.outputDir, |
| 56 | + clearTerminalOnReload: false, |
| 57 | + }; |
| 58 | + |
| 59 | + try { |
| 60 | + this.devServer = await startDevServer({ |
| 61 | + config, |
| 62 | + logStartMessage: false, |
| 63 | + readCliArgs: false, |
| 64 | + readFileConfig: false, |
| 65 | + // argv: this.__argv, |
| 66 | + }); |
| 67 | + logPreviewMessage({ devServerOptions: this.devServer.config }, console); |
| 68 | + } catch (e) { |
| 69 | + console.log('🛑 Starting preview server failed'); |
| 70 | + console.error(e); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + async stop() { |
| 75 | + if (this.devServer) { |
| 76 | + await this.devServer.stop(); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments