|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +function getWebpackDevServerMajorVersion() { |
| 4 | + try { |
| 5 | + const pkgJson = require("webpack-dev-server/package.json"); |
| 6 | + if (!pkgJson || typeof pkgJson.version !== "string") { |
| 7 | + return null; |
| 8 | + } |
| 9 | + const major = Number.parseInt(pkgJson.version.split(".")[0], 10); |
| 10 | + return Number.isNaN(major) ? null : major; |
| 11 | + } catch (error) { |
| 12 | + return null; |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +function patchWebpackDevServerConfig() { |
| 17 | + const major = getWebpackDevServerMajorVersion(); |
| 18 | + if (major === null || major < 5) { |
| 19 | + return; |
| 20 | + } |
| 21 | + |
| 22 | + const configPath = require.resolve( |
| 23 | + "react-scripts/config/webpackDevServer.config", |
| 24 | + ); |
| 25 | + const originalFactory = require(configPath); |
| 26 | + |
| 27 | + const patchedFactory = (proxy, allowedHost) => { |
| 28 | + const originalConfig = originalFactory(proxy, allowedHost); |
| 29 | + |
| 30 | + const { |
| 31 | + https: httpsOption, |
| 32 | + onBeforeSetupMiddleware: onBefore, |
| 33 | + onAfterSetupMiddleware: onAfter, |
| 34 | + setupMiddlewares: originalSetup, |
| 35 | + ...restConfig |
| 36 | + } = originalConfig; |
| 37 | + |
| 38 | + const config = { ...restConfig }; |
| 39 | + const existingSetup = |
| 40 | + typeof originalSetup === "function" ? originalSetup : null; |
| 41 | + |
| 42 | + if ( |
| 43 | + Object.prototype.hasOwnProperty.call(originalConfig, "https") && |
| 44 | + httpsOption |
| 45 | + ) { |
| 46 | + config.server = |
| 47 | + typeof httpsOption === "object" |
| 48 | + ? { type: "https", options: httpsOption } |
| 49 | + : "https"; |
| 50 | + } |
| 51 | + |
| 52 | + if (typeof onBefore === "function" || typeof onAfter === "function") { |
| 53 | + config.setupMiddlewares = (middlewares, devServer) => { |
| 54 | + let resolvedMiddlewares = middlewares; |
| 55 | + |
| 56 | + if (existingSetup) { |
| 57 | + const result = existingSetup(middlewares, devServer); |
| 58 | + if (Array.isArray(result)) { |
| 59 | + resolvedMiddlewares = result; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + if (!devServer) { |
| 64 | + return resolvedMiddlewares; |
| 65 | + } |
| 66 | + |
| 67 | + if (typeof onBefore === "function") { |
| 68 | + onBefore(devServer); |
| 69 | + } |
| 70 | + |
| 71 | + if (typeof onAfter === "function") { |
| 72 | + onAfter(devServer); |
| 73 | + } |
| 74 | + |
| 75 | + return resolvedMiddlewares; |
| 76 | + }; |
| 77 | + } else if (existingSetup) { |
| 78 | + config.setupMiddlewares = existingSetup; |
| 79 | + } |
| 80 | + |
| 81 | + return config; |
| 82 | + }; |
| 83 | + |
| 84 | + require.cache[configPath].exports = patchedFactory; |
| 85 | +} |
| 86 | + |
| 87 | +patchWebpackDevServerConfig(); |
| 88 | + |
| 89 | +require("react-scripts/scripts/start"); |
0 commit comments