Skip to content

Instantly share code, notes, and snippets.

@gionkunz
Created April 26, 2022 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gionkunz/89597fd2d3828a15791e1878670ddaa1 to your computer and use it in GitHub Desktop.
Save gionkunz/89597fd2d3828a15791e1878670ddaa1 to your computer and use it in GitHub Desktop.
Angular Devkit like HTTP Proxy for Nx @nrwl/web:file-server
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);
// 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