-
Notifications
You must be signed in to change notification settings - Fork 3
/
monkey.ts
100 lines (82 loc) · 2.92 KB
/
monkey.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
90
91
92
93
94
95
96
97
98
99
100
import { isFunction, isNil, isObject, isPlainObject } from "lodash"
import { Configuration } from "webpack"
import { merge } from "webpack-merge"
import { MonkeyMinimizer, MonkeyMinimizerOptions } from "./MonkeyMinimizer"
import { MonkeyPlugin, MonkeyPluginOptions } from "./MonkeyPlugin"
interface MonkeyOptions extends MonkeyPluginOptions, MonkeyMinimizerOptions {}
export function monkey({
monkey: options,
...config
}: Configuration & {
monkey?: MonkeyOptions
} = {}): Configuration {
const plugin = new MonkeyPlugin(options)
const userDefinedRuntimeChunk = config?.optimization?.runtimeChunk
if (!isNil(userDefinedRuntimeChunk)) {
console.warn(
MonkeyPlugin.name +
`: the value of "optimization.runtimeChunk" will be ignored. It will be overwritten to "single" when serving, and "false" when building.`,
)
}
const userDefinedExternals = config?.externals
if (
!isNil(userDefinedExternals) &&
!isPlainObject(userDefinedExternals) &&
!isFunction(userDefinedExternals)
) {
throw new Error(MonkeyPlugin.name + `: "externals" must be an object or a function.`)
}
let devClient = config?.devServer?.client
if (!isObject(devClient)) {
devClient = {}
}
return merge(
{
devServer: {
hot: "only",
},
output: {
filename: "[name].user.js",
},
},
// ====================================================
config,
// ====================================================
{
plugins: [plugin],
devServer: {
webSocketServer: "sockjs",
client: {
...devClient,
webSocketTransport: "sockjs",
webSocketURL: {
port: config?.devServer?.port,
...(isObject(devClient.webSocketURL) ? devClient.webSocketURL : null),
protocol: "ws",
// TODO: SockJS will throw if the hostname is not a loopback address,
// maybe we can patch it to allow other hostnames e.g. "localhost"
hostname: "127.0.0.1",
},
},
setupMiddlewares: (middlewares, server) => {
plugin["setupServeMode"](server)
return config.devServer?.setupMiddlewares?.(middlewares, server) ?? middlewares
},
},
optimization: {
runtimeChunk: {
name: () => plugin.getRuntimeName(),
},
minimizer: [new MonkeyMinimizer(options)],
// by default this is false in development mode, we turn it on to allow the plugin to
// detect unexpected used exports unnamed external modules and then warn the user
// TODO: this may lower the performance, maybe find a solution that doesn't require this option
usedExports: options?.require?.exportsFromUnnamed ? undefined : true,
},
externalsType: "var",
externals: (data, callback) => {
return plugin.resolveExternals(data, callback, userDefinedExternals as any)
},
},
)
}