-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
269 lines (248 loc) · 8.97 KB
/
index.js
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
const fs = require("fs");
const path = require("path");
const { paths } = require("react-app-rewired");
const webpack = require("webpack");
const SystemJSPublicPathPlugin = require("systemjs-webpack-interop/SystemJSPublicPathWebpackPlugin");
module.exports.rewiredSingleSpa = rewiredSingleSpa;
module.exports.rewiredSingleSpaDevServer = rewiredSingleSpaDevServer;
function rewiredSingleSpa({
orgName,
projectName,
entry,
outputFilename,
rootDirectoryLevel,
reactPackagesAsExternal,
orgPackagesAsExternal,
peerDepsAsExternal,
}) {
if (typeof orgName !== "string") {
throw Error(
`react-app-rewired-single-spa params requires "orgName" string`
);
}
if (typeof projectName !== "string") {
throw Error(
`react-app-rewired-single-spa params requires "projectName" string`
);
}
const webpackMajorVersion = getWebpackMajorVersion();
const combinedName = `${orgName}-${projectName}`;
const pkgJson = require(paths.appPackageJson);
const inputEntry = entry
? path.resolve(entry)
: getExistFile({
cwd: process.cwd(),
returnRelative: true,
files: [
`src/${combinedName}.jsx`,
`src/${combinedName}.tsx`,
`src/${combinedName}.js`,
`src/${combinedName}.ts`,
"src/index.jsx",
"src/index.tsx",
"src/index.ts",
"src/index.js",
],
});
return function (config, webpackEnv = process.env.BABEL_ENV) {
const isEnvProduction = webpackEnv === "production";
const isFastRefresh = process.env.FAST_REFRESH !== "false";
// amend input output
config.output = {
...config.output,
filename: `${outputFilename || combinedName}${isEnvProduction ? ".[contenthash:8]" : ""
}.js`,
publicPath: paths.publicUrlOrPath,
libraryTarget: "system",
devtoolNamespace: `${orgName}-${projectName}`,
};
if (webpackMajorVersion < 5) {
// support reactFastRefresh
config.entry =
isEnvProduction || !isFastRefresh
? inputEntry
: ["react-dev-utils/webpackHotDevClient", inputEntry];
config.output.jsonpFunction = `webpackJsonp_${safeVarName(projectName)}`;
config.output.hotUpdateFunction = `webpackHotUpdate_${safeVarName(
projectName
)}`;
} else {
config.entry = inputEntry;
config.output.chunkLoadingGlobal = `webpackJsonp_${safeVarName(
projectName
)}`;
config.output.hotUpdateGlobal = `webpackHotUpdate_${safeVarName(
projectName
)}`;
// window will become globalThis
config.output.globalObject = "self";
}
// amend module
if (webpackMajorVersion < 5) {
// @see https://github.com/systemjs/systemjs#compatibility-with-webpack
config.module.rules.unshift({ parser: { system: false } });
}
// amend optimization
config.optimization.splitChunks = {
chunks: "async",
cacheGroups: { default: false },
};
if (webpackMajorVersion < 5) {
config.optimization.namedModules = true;
config.optimization.namedChunks = true;
} else {
config.optimization.moduleIds = "named";
config.optimization.chunkIds = "named";
}
delete config.optimization.runtimeChunk;
// amend plugins
const plugins = config.plugins.filter((plugin) => {
return ![
"HtmlWebpackPlugin",
"GenerateSW",
"InterpolateHtmlPlugin",
"MiniCssExtractPlugin",
].includes(plugin.constructor.name);
});
plugins.push(
new SystemJSPublicPathPlugin({
systemjsModuleName: `@${orgName}/${projectName}`,
rootDirectoryLevel: rootDirectoryLevel,
})
);
config.plugins = plugins;
// process externals
const externals = [];
if (config.externals) {
if (Array.isArray(config.externals)) {
externals.push(...config.externals);
} else {
externals.push(config.externals);
}
}
if (!!reactPackagesAsExternal) {
externals.push("react", "react-dom");
}
if (!!orgPackagesAsExternal) {
externals.push(new RegExp(`^@${orgName}/`));
}
if (!!peerDepsAsExternal) {
externals.push(...Object.keys(pkgJson.peerDependencies || {}));
}
externals.push("single-spa");
config.externals = externals;
// process alias
if (webpackMajorVersion < 5) {
Object.assign(config.resolve.alias, {
// alias parcel
"single-spa-react/parcel": "single-spa-react/lib/esm/parcel.js",
});
}
disableCSSExtraction(config);
// for wp5
// https://stackoverflow.com/questions/64557638/how-to-polyfill-node-core-modules-in-webpack-5
if (webpackMajorVersion == 5) {
config.plugins.push(
new webpack.ProvidePlugin({
process: "process/browser.js",
Buffer: ["buffer", "Buffer"],
})
);
config.resolve.fallback = Object.assign(
config.resolve.fallback || {},
// @see https://github.com/webpack/webpack/blob/c181294865dca01b28e6e316636fef5f2aad4eb6/lib/ModuleNotFoundError.js
getFallbackObj({
assert: 'assert/',
buffer: 'buffer/',
console: 'console-browserify',
constants: 'constants-browserify',
crypto: 'crypto-browserify',
domain: 'domain-browser',
events: 'events/',
http: 'stream-http',
https: 'https-browserify',
os: 'os-browserify/browser',
path: 'path-browserify',
punycode: 'punycode/',
process: 'process/browser',
querystring: 'querystring-es3',
stream: 'stream-browserify',
_stream_duplex: 'readable-stream/duplex',
_stream_passthrough: 'readable-stream/passthrough',
_stream_readable: 'readable-stream/readable',
_stream_transform: 'readable-stream/transform',
_stream_writable: 'readable-stream/writable',
string_decoder: 'string_decoder/',
sys: 'util/',
timers: 'timers-browserify',
tty: 'tty-browserify',
url: 'url/',
util: 'util/',
vm: 'vm-browserify',
zlib: 'browserify-zlib',
})
);
}
return config;
};
}
function rewiredSingleSpaDevServer() {
const webpackMajorVersion = getWebpackMajorVersion();
return function (config) {
config.historyApiFallback = true;
if (webpackMajorVersion < 5) {
config.headers = {
...config.headers,
"Access-Control-Allow-Origin": "*",
};
config.compress = true;
} else {
config.allowedHosts = "all";
config.webSocketServer = {
type: "ws",
options: { path: process.env.WDS_SOCKET_PATH || "/ws" },
};
}
return config;
};
}
function getWebpackMajorVersion() {
return webpack.version.split(".")[0];
}
function safeVarName(key) {
return key.replace(/(\/|\@|\-)/g, "_");
}
function getExistFile({ cwd, files, returnRelative }) {
for (const file of files) {
const absFilePath = path.join(cwd, file);
if (fs.existsSync(absFilePath)) {
return returnRelative ? file : absFilePath;
}
}
}
function disableCSSExtraction(config) {
for (const rule of config.module.rules) {
if (rule.oneOf) {
rule.oneOf.forEach((x) => {
if (x.use && Array.isArray(x.use)) {
x.use.forEach((use) => {
if (use.loader && use.loader.includes("mini-css-extract-plugin")) {
use.loader = require.resolve("style-loader/dist/cjs.js");
delete use.options;
}
});
}
});
}
}
}
function getFallbackObj(obj) {
const res = {};
for (const [k, v] of Object.entries(obj)) {
try {
const p = require.resolve(v);
p && (res[k] = p);
} catch (e) { }
}
return res;
}