UNPKG

2.94 kBPlain TextView Raw
1import { DevServer } from '@web/dev-server-core';
2import { DevServerConfig } from './config/DevServerConfig.js';
3import { mergeConfigs } from './config/mergeConfigs.js';
4import { parseConfig } from './config/parseConfig.js';
5import { readCliArgs } from './config/readCliArgs.js';
6import { readFileConfig } from './config/readFileConfig.js';
7import { DevServerStartError } from './DevServerStartError.js';
8import { createLogger } from './logger/createLogger.js';
9import { openBrowser } from './openBrowser.js';
10
11export interface StartDevServerParams {
12 /**
13 * Optional config to merge with the user-defined config.
14 */
15 config?: Partial<DevServerConfig>;
16 /**
17 * Whether to read CLI args. Default true.
18 */
19 readCliArgs?: boolean;
20 /**
21 * Whether to read a user config from the file system. Default true.
22 */
23 readFileConfig?: boolean;
24 /**
25 * Name of the configuration to read. Defaults to web-dev-server.config.{mjs,cjs,js}
26 */
27 configName?: string;
28 /**
29 * Whether to automatically exit the process when the server is stopped, killed or an error is thrown.
30 */
31 autoExitProcess?: boolean;
32 /**
33 * Whether to log a message when the server is started.
34 */
35 logStartMessage?: boolean;
36 /**
37 * Array to read the CLI args from. Defaults to process.argv.
38 */
39 argv?: string[];
40}
41
42/**
43 * Starts the dev server.
44 */
45export async function startDevServer(options: StartDevServerParams = {}) {
46 const {
47 config: extraConfig,
48 readCliArgs: readCliArgsFlag = true,
49 readFileConfig: readFileConfigFlag = true,
50 configName,
51 autoExitProcess = true,
52 logStartMessage = true,
53 argv = process.argv,
54 } = options;
55
56 try {
57 const cliArgs = readCliArgsFlag ? readCliArgs({ argv }) : {};
58 const rawConfig = readFileConfigFlag
59 ? await readFileConfig({ configName, configPath: cliArgs.config })
60 : {};
61 const mergedConfig = mergeConfigs(extraConfig, rawConfig);
62 const config = await parseConfig(mergedConfig, cliArgs);
63
64 const { logger, loggerPlugin } = createLogger({
65 debugLogging: !!config.debug,
66 clearTerminalOnReload: !!config.watch && !!config.clearTerminalOnReload,
67 logStartMessage: !!logStartMessage,
68 });
69 config.plugins = config.plugins ?? [];
70 config.plugins.unshift(loggerPlugin);
71
72 const server = new DevServer(config, logger);
73
74 if (autoExitProcess) {
75 process.on('uncaughtException', error => {
76 /* eslint-disable-next-line no-console */
77 console.error(error);
78 });
79
80 process.on('SIGINT', async () => {
81 await server.stop();
82 process.exit(0);
83 });
84 }
85
86 await server.start();
87
88 if (config.open != null && config.open !== false) {
89 await openBrowser(config);
90 }
91
92 return server;
93 } catch (error) {
94 if (error instanceof DevServerStartError) {
95 console.error(error.message);
96 } else {
97 console.error(error);
98 }
99 process.exit(1);
100 }
101}