Created
April 26, 2022 12:06
-
-
Save gionkunz/89597fd2d3828a15791e1878670ddaa1 to your computer and use it in GitHub Desktop.
Angular Devkit like HTTP Proxy for Nx @nrwl/web:file-server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as express from 'express'; | |
import { join } from 'path'; | |
import { getProxyConfig } from './webpack-dev-server-proxy-conf'; | |
function error(message: string): never { | |
throw new Error(message); | |
} | |
const proxyConfigPath = process.argv[2] || error('Please specify proxy config path as argument.'); | |
const createProxyMiddleware = require('http-proxy-middleware'); | |
const app = express(); | |
const config = getProxyConfig(require(join(process.cwd(), proxyConfigPath))); | |
config.forEach((item) => app.use(item.context, createProxyMiddleware(item.context, item))); | |
app.listen(3000); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copied from in order to mimic webpack-dev-server proxy config handling | |
// https://github.com/webpack/webpack-dev-server/blob/master/lib/Server.js#L1379 | |
export interface ProxyConfigItem { | |
readonly context: string; | |
readonly target: string; | |
readonly secure?: boolean; | |
readonly changeOrigin?: boolean; | |
readonly pathRewrite?: { | |
[k: string]: string; | |
}; | |
} | |
export function getProxyConfig(proxyConfig: any): ProxyConfigItem[] { | |
return Object.keys(proxyConfig).map( | |
/** | |
* @param {string} context | |
* @returns {HttpProxyMiddlewareOptions} | |
*/ | |
(context) => { | |
let proxyOptions; | |
// For backwards compatibility reasons. | |
const correctedContext = context.replace(/^\*$/, '**').replace(/\/\*$/, ''); | |
if (typeof (/** @type {ProxyConfigMap} */ proxyConfig[context]) === 'string') { | |
proxyOptions = { | |
context: correctedContext, | |
target: | |
/** @type {ProxyConfigMap} */ | |
proxyConfig[context] | |
}; | |
} else { | |
proxyOptions = { | |
// @ts-ignore | |
.../** @type {ProxyConfigMap} */ proxyConfig[context] | |
}; | |
proxyOptions.context = correctedContext; | |
} | |
return proxyOptions; | |
} | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment