-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathdevServer.ts
More file actions
86 lines (79 loc) · 2.55 KB
/
Copy pathdevServer.ts
File metadata and controls
86 lines (79 loc) · 2.55 KB
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
import type { WebpackBuildConfig } from '../../../shared';
import pc from 'picocolors';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
interface StartDevServerOptions {
webpackConfig: webpack.Configuration;
host: string;
port: number;
proxy: any;
https: boolean | { key: string; cert: string };
beforeMiddlewares: any[];
afterMiddlewares: any[];
customerDevServerConfig?: WebpackBuildConfig['devServer'];
}
function formatProxy(proxy: any) {
if (!proxy) {
return [];
}
if (Array.isArray(proxy)) {
return proxy;
}
return Object.keys(proxy).map((apiPath) => {
return {
context: [apiPath],
...proxy[apiPath],
};
});
}
export function startDevServer({ webpackConfig, host, port, proxy, https, beforeMiddlewares, afterMiddlewares, customerDevServerConfig }: StartDevServerOptions) {
const headers: Record<string, string> = {
'access-control-allow-origin': '*',
};
const options: WebpackDevServer.Configuration = {
hot: true,
allowedHosts: 'all',
server: https ? 'https' : 'http',
client: {
logging: 'error',
overlay: false,
progress: true,
webSocketURL: {
hostname: host,
port,
},
},
setupMiddlewares(middlewares) {
middlewares.unshift(...beforeMiddlewares);
middlewares.push(...afterMiddlewares);
return middlewares;
},
// @ts-expect-error 不知道这里为啥异常
headers,
...(customerDevServerConfig || {}),
port,
host,
proxy: formatProxy(proxy),
};
const compiler = webpack(webpackConfig);
if (!compiler) {
throw new Error('Failed to create webpack compiler');
}
const server = new WebpackDevServer(options, compiler);
if (options.host === '0.0.0.0') {
// eslint-disable-next-line no-console
console.log(pc.green(' ➜ Local: '), pc.cyan(`${options.server}://127.0.0.1:${options.port}`));
// eslint-disable-next-line no-console
console.log(pc.gray(' ➜ Network: '), pc.gray(`${options.server}://${options.host}:${options.port}`));
}
else {
// eslint-disable-next-line no-console
console.log(pc.green(' ➜ :Local: '), pc.cyan(`${options.server}://${options.host}:${options.port}`));
}
server.startCallback((err) => {
if (err) {
console.error(err);
}
});
return server;
}