-
Notifications
You must be signed in to change notification settings - Fork 34
/
utils.ts
89 lines (80 loc) · 2.83 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import WebpackDevServer from 'webpack-dev-server';
import {internalIpV4} from 'internal-ip';
import {readProjectSettings, BuildEnv, strictCheckRequiredDependency} from '@reskript/settings';
import {BuildContext, collectEntries, createRuntimeBuildEnv, EntryLocation} from '@reskript/config-webpack';
import {logger, readPackageConfig} from '@reskript/core';
import {DevCommandLineArgs} from './interface.js';
export const resolveHost = async (hostType: DevCommandLineArgs['host']) => {
if (!hostType) {
return 'localhost';
}
switch (hostType) {
case 'localhost':
return 'localhost';
case 'loopback':
return '127.0.0.1';
case 'ip': {
const ip = await internalIpV4();
return ip ?? 'localhost';
}
default:
return hostType;
}
};
export const resolvePublicPath = async (hostType: DevCommandLineArgs['host'], port: number) => {
if (!hostType) {
return undefined;
}
const host = await resolveHost(hostType);
return `http://${host}:${port}/assets/`;
};
export const startServer = async (server: WebpackDevServer): Promise<void> => {
try {
await server.start();
}
catch (ex) {
logger.error(ex instanceof Error ? ex.message : `${ex}`);
process.exit(22);
}
};
export const createBuildContext = async (cmd: DevCommandLineArgs): Promise<BuildContext> => {
const [
projectSettings,
{name: hostPackageName},
] = await Promise.all([readProjectSettings(cmd, 'dev'), readPackageConfig(cmd.cwd)]);
await strictCheckRequiredDependency(projectSettings, cmd.cwd);
const entryLocation: EntryLocation = {
cwd: cmd.cwd,
srcDirectory: cmd.srcDirectory,
entryDirectory: cmd.entriesDirectory,
only: [cmd.entry],
};
const entries = await collectEntries(entryLocation);
if (!entries.length) {
logger.error(`You have specified a missing entry ${cmd.entry}, dev-server is unable to start.`);
process.exit(21);
}
const buildEnv: BuildEnv = {
hostPackageName,
usage: 'devServer',
mode: cmd.mode ?? 'development',
cwd: cmd.cwd,
srcDirectory: cmd.srcDirectory,
// `react-refresh`无法在`production`模式下工作,所以在该模式下直接禁用掉热更新
projectSettings: {
...projectSettings,
devServer: {
...projectSettings.devServer,
hot: cmd.mode === 'production' ? false : projectSettings.devServer.hot,
},
},
};
const runtimeBuildEnv = await createRuntimeBuildEnv(buildEnv);
return {
...runtimeBuildEnv,
entries,
features: projectSettings.featureMatrix[cmd.buildTarget],
buildTarget: cmd.buildTarget || 'dev',
isDefaultTarget: true,
};
};