mirror of
https://github.com/aspnet/JavaScriptServices.git
synced 2025-12-24 10:40:23 +00:00
refactor: apply default vs transform to xproj
refactor(spa-services): clean code refactor(node-services): clean code, extract classes nto separate files refactor(angular-services): prime cache cleanup
This commit is contained in:
@@ -9,11 +9,10 @@
|
||||
<ProjectGuid>4624f728-6dff-44b6-93b5-3c7d9c94bf3f</ProjectGuid>
|
||||
<RootNamespace>Microsoft.AspNetCore.SpaServices</RootNamespace>
|
||||
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
|
||||
<OutputPath Condition="'$(OutputPath)'=='' ">..\artifacts\bin\$(MSBuildProjectName)\</OutputPath>
|
||||
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
|
||||
</Project>
|
||||
</Project>
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Microsoft.AspNetCore.SpaServices.Prerendering
|
||||
{
|
||||
public class JavaScriptModuleExport
|
||||
{
|
||||
public JavaScriptModuleExport(string moduleName)
|
||||
{
|
||||
this.ModuleName = moduleName;
|
||||
}
|
||||
|
||||
public string ModuleName { get; private set; }
|
||||
public string ExportName { get; set; }
|
||||
public string WebpackConfig { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -16,11 +16,31 @@ namespace Microsoft.AspNetCore.SpaServices.Prerendering
|
||||
[HtmlTargetElement(Attributes = PrerenderModuleAttributeName)]
|
||||
public class PrerenderTagHelper : TagHelper
|
||||
{
|
||||
static INodeServices fallbackNodeServices; // Used only if no INodeServices was registered with DI
|
||||
private const string PrerenderModuleAttributeName = "asp-prerender-module";
|
||||
private const string PrerenderExportAttributeName = "asp-prerender-export";
|
||||
private const string PrerenderWebpackConfigAttributeName = "asp-prerender-webpack-config";
|
||||
private static INodeServices _fallbackNodeServices; // Used only if no INodeServices was registered with DI
|
||||
|
||||
const string PrerenderModuleAttributeName = "asp-prerender-module";
|
||||
const string PrerenderExportAttributeName = "asp-prerender-export";
|
||||
const string PrerenderWebpackConfigAttributeName = "asp-prerender-webpack-config";
|
||||
private readonly string _applicationBasePath;
|
||||
private readonly INodeServices _nodeServices;
|
||||
|
||||
public PrerenderTagHelper(IServiceProvider serviceProvider)
|
||||
{
|
||||
var hostEnv = (IHostingEnvironment) serviceProvider.GetService(typeof(IHostingEnvironment));
|
||||
_nodeServices = (INodeServices) serviceProvider.GetService(typeof(INodeServices)) ?? _fallbackNodeServices;
|
||||
_applicationBasePath = hostEnv.ContentRootPath;
|
||||
|
||||
// Consider removing the following. Having it means you can get away with not putting app.AddNodeServices()
|
||||
// in your startup file, but then again it might be confusing that you don't need to.
|
||||
if (_nodeServices == null)
|
||||
{
|
||||
_nodeServices = _fallbackNodeServices = Configuration.CreateNodeServices(new NodeServicesOptions
|
||||
{
|
||||
HostingModel = NodeHostingModel.Http,
|
||||
ProjectPath = _applicationBasePath
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
[HtmlAttributeName(PrerenderModuleAttributeName)]
|
||||
public string ModuleName { get; set; }
|
||||
@@ -35,52 +55,37 @@ namespace Microsoft.AspNetCore.SpaServices.Prerendering
|
||||
[ViewContext]
|
||||
public ViewContext ViewContext { get; set; }
|
||||
|
||||
private string applicationBasePath;
|
||||
private INodeServices nodeServices;
|
||||
|
||||
public PrerenderTagHelper(IServiceProvider serviceProvider)
|
||||
{
|
||||
var hostEnv = (IHostingEnvironment)serviceProvider.GetService(typeof (IHostingEnvironment));
|
||||
this.nodeServices = (INodeServices)serviceProvider.GetService(typeof (INodeServices)) ?? fallbackNodeServices;
|
||||
this.applicationBasePath = hostEnv.ContentRootPath;
|
||||
|
||||
// Consider removing the following. Having it means you can get away with not putting app.AddNodeServices()
|
||||
// in your startup file, but then again it might be confusing that you don't need to.
|
||||
if (this.nodeServices == null) {
|
||||
this.nodeServices = fallbackNodeServices = Configuration.CreateNodeServices(new NodeServicesOptions {
|
||||
HostingModel = NodeHostingModel.Http,
|
||||
ProjectPath = this.applicationBasePath
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
|
||||
{
|
||||
var request = this.ViewContext.HttpContext.Request;
|
||||
var request = ViewContext.HttpContext.Request;
|
||||
var result = await Prerenderer.RenderToString(
|
||||
applicationBasePath: this.applicationBasePath,
|
||||
nodeServices: this.nodeServices,
|
||||
bootModule: new JavaScriptModuleExport(this.ModuleName) {
|
||||
exportName = this.ExportName,
|
||||
webpackConfig = this.WebpackConfigPath
|
||||
_applicationBasePath,
|
||||
_nodeServices,
|
||||
new JavaScriptModuleExport(ModuleName)
|
||||
{
|
||||
ExportName = ExportName,
|
||||
WebpackConfig = WebpackConfigPath
|
||||
},
|
||||
requestAbsoluteUrl: UriHelper.GetEncodedUrl(request),
|
||||
requestPathAndQuery: request.Path + request.QueryString.Value);
|
||||
request.GetEncodedUrl(),
|
||||
request.Path + request.QueryString.Value);
|
||||
output.Content.SetHtmlContent(result.Html);
|
||||
|
||||
// Also attach any specified globals to the 'window' object. This is useful for transferring
|
||||
// general state between server and client.
|
||||
if (result.Globals != null) {
|
||||
if (result.Globals != null)
|
||||
{
|
||||
var stringBuilder = new StringBuilder();
|
||||
foreach (var property in result.Globals.Properties()) {
|
||||
foreach (var property in result.Globals.Properties())
|
||||
{
|
||||
stringBuilder.AppendFormat("window.{0} = {1};",
|
||||
property.Name,
|
||||
property.Value.ToString(Formatting.None));
|
||||
}
|
||||
if (stringBuilder.Length > 0) {
|
||||
output.PostElement.SetHtmlContent($"<script>{ stringBuilder.ToString() }</script>");
|
||||
if (stringBuilder.Length > 0)
|
||||
{
|
||||
output.PostElement.SetHtmlContent($"<script>{stringBuilder}</script>");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,42 +1,34 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.NodeServices;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Microsoft.AspNetCore.SpaServices.Prerendering
|
||||
{
|
||||
public static class Prerenderer
|
||||
{
|
||||
private static Lazy<StringAsTempFile> nodeScript;
|
||||
private static readonly Lazy<StringAsTempFile> NodeScript;
|
||||
|
||||
static Prerenderer() {
|
||||
nodeScript = new Lazy<StringAsTempFile>(() => {
|
||||
static Prerenderer()
|
||||
{
|
||||
NodeScript = new Lazy<StringAsTempFile>(() =>
|
||||
{
|
||||
var script = EmbeddedResourceReader.Read(typeof(Prerenderer), "/Content/Node/prerenderer.js");
|
||||
return new StringAsTempFile(script); // Will be cleaned up on process exit
|
||||
});
|
||||
}
|
||||
|
||||
public static async Task<RenderToStringResult> RenderToString(string applicationBasePath, INodeServices nodeServices, JavaScriptModuleExport bootModule, string requestAbsoluteUrl, string requestPathAndQuery) {
|
||||
return await nodeServices.InvokeExport<RenderToStringResult>(nodeScript.Value.FileName, "renderToString",
|
||||
public static async Task<RenderToStringResult> RenderToString(
|
||||
string applicationBasePath,
|
||||
INodeServices nodeServices,
|
||||
JavaScriptModuleExport bootModule,
|
||||
string requestAbsoluteUrl,
|
||||
string requestPathAndQuery)
|
||||
=> await nodeServices.InvokeExport<RenderToStringResult>(
|
||||
NodeScript.Value.FileName,
|
||||
"renderToString",
|
||||
applicationBasePath,
|
||||
bootModule,
|
||||
requestAbsoluteUrl,
|
||||
requestPathAndQuery);
|
||||
}
|
||||
}
|
||||
|
||||
public class JavaScriptModuleExport {
|
||||
public string moduleName { get; private set; }
|
||||
public string exportName { get; set; }
|
||||
public string webpackConfig { get; set; }
|
||||
|
||||
public JavaScriptModuleExport(string moduleName) {
|
||||
this.moduleName = moduleName;
|
||||
}
|
||||
}
|
||||
|
||||
public class RenderToStringResult {
|
||||
public string Html;
|
||||
public JObject Globals;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Microsoft.AspNetCore.SpaServices.Prerendering
|
||||
{
|
||||
public class RenderToStringResult
|
||||
{
|
||||
public JObject Globals { get; set; }
|
||||
public string Html { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
@@ -7,26 +6,27 @@ namespace Microsoft.AspNetCore.SpaServices
|
||||
{
|
||||
internal class SpaRouteConstraint : IRouteConstraint
|
||||
{
|
||||
private readonly string clientRouteTokenName;
|
||||
private readonly string _clientRouteTokenName;
|
||||
|
||||
public SpaRouteConstraint(string clientRouteTokenName) {
|
||||
if (string.IsNullOrEmpty(clientRouteTokenName)) {
|
||||
throw new ArgumentException("Value cannot be null or empty", "clientRouteTokenName");
|
||||
public SpaRouteConstraint(string clientRouteTokenName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(clientRouteTokenName))
|
||||
{
|
||||
throw new ArgumentException("Value cannot be null or empty", nameof(clientRouteTokenName));
|
||||
}
|
||||
|
||||
this.clientRouteTokenName = clientRouteTokenName;
|
||||
_clientRouteTokenName = clientRouteTokenName;
|
||||
}
|
||||
|
||||
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
|
||||
{
|
||||
var clientRouteValue = (values[this.clientRouteTokenName] as string) ?? string.Empty;
|
||||
return !HasDotInLastSegment(clientRouteValue);
|
||||
}
|
||||
public bool Match(
|
||||
HttpContext httpContext,
|
||||
IRouter route,
|
||||
string routeKey,
|
||||
RouteValueDictionary values,
|
||||
RouteDirection routeDirection)
|
||||
=> !HasDotInLastSegment(values[_clientRouteTokenName] as string ?? string.Empty);
|
||||
|
||||
private bool HasDotInLastSegment(string uri)
|
||||
{
|
||||
var lastSegmentStartPos = uri.LastIndexOf('/');
|
||||
return uri.IndexOf('.', lastSegmentStartPos + 1) >= 0;
|
||||
}
|
||||
=> uri.IndexOf('.', uri.LastIndexOf('/') + 1) >= 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,18 +4,34 @@ using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.AspNetCore.SpaServices;
|
||||
|
||||
// Putting in this namespace so it's always available whenever MapRoute is
|
||||
|
||||
namespace Microsoft.AspNetCore.Builder
|
||||
{
|
||||
public static class SpaRouteExtensions
|
||||
{
|
||||
private const string ClientRouteTokenName = "clientRoute";
|
||||
|
||||
public static void MapSpaFallbackRoute(this IRouteBuilder routeBuilder, string name, object defaults, object constraints = null, object dataTokens = null)
|
||||
{
|
||||
MapSpaFallbackRoute(routeBuilder, name, /* templatePrefix */ (string)null, defaults, constraints, dataTokens);
|
||||
}
|
||||
public static void MapSpaFallbackRoute(
|
||||
this IRouteBuilder routeBuilder,
|
||||
string name,
|
||||
object defaults,
|
||||
object constraints = null,
|
||||
object dataTokens = null)
|
||||
=> MapSpaFallbackRoute(
|
||||
routeBuilder,
|
||||
name,
|
||||
/* templatePrefix */ null,
|
||||
defaults,
|
||||
constraints,
|
||||
dataTokens);
|
||||
|
||||
public static void MapSpaFallbackRoute(this IRouteBuilder routeBuilder, string name, string templatePrefix, object defaults, object constraints = null, object dataTokens = null)
|
||||
public static void MapSpaFallbackRoute(
|
||||
this IRouteBuilder routeBuilder,
|
||||
string name,
|
||||
string templatePrefix,
|
||||
object defaults,
|
||||
object constraints = null,
|
||||
object dataTokens = null)
|
||||
{
|
||||
var template = CreateRouteTemplate(templatePrefix);
|
||||
|
||||
@@ -29,25 +45,27 @@ namespace Microsoft.AspNetCore.Builder
|
||||
{
|
||||
templatePrefix = templatePrefix ?? string.Empty;
|
||||
|
||||
if (templatePrefix.Contains("?")) {
|
||||
if (templatePrefix.Contains("?"))
|
||||
{
|
||||
// TODO: Consider supporting this. The {*clientRoute} part should be added immediately before the '?'
|
||||
throw new ArgumentException("SPA fallback route templates don't support querystrings");
|
||||
}
|
||||
|
||||
if (templatePrefix.Contains("#")) {
|
||||
throw new ArgumentException("SPA fallback route templates should not include # characters. The hash part of a URI does not get sent to the server.");
|
||||
if (templatePrefix.Contains("#"))
|
||||
{
|
||||
throw new ArgumentException(
|
||||
"SPA fallback route templates should not include # characters. The hash part of a URI does not get sent to the server.");
|
||||
}
|
||||
|
||||
if (templatePrefix != string.Empty && !templatePrefix.EndsWith("/")) {
|
||||
if (templatePrefix != string.Empty && !templatePrefix.EndsWith("/"))
|
||||
{
|
||||
templatePrefix += "/";
|
||||
}
|
||||
|
||||
return templatePrefix + $"{{*{ ClientRouteTokenName }}}";
|
||||
return templatePrefix + $"{{*{ClientRouteTokenName}}}";
|
||||
}
|
||||
|
||||
private static IDictionary<string, object> ObjectToDictionary(object value)
|
||||
{
|
||||
return value as IDictionary<string, object> ?? new RouteValueDictionary(value);
|
||||
}
|
||||
=> value as IDictionary<string, object> ?? new RouteValueDictionary(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,65 +8,85 @@ using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Microsoft.AspNetCore.SpaServices.Webpack
|
||||
{
|
||||
// Based on https://github.com/aspnet/Proxy/blob/dev/src/Microsoft.AspNetCore.Proxy/ProxyMiddleware.cs
|
||||
// Differs in that, if the proxied request returns a 404, we pass through to the next middleware in the chain
|
||||
// This is useful for Webpack middleware, because it lets you fall back on prebuilt files on disk for
|
||||
// chunks not exposed by the current Webpack config (e.g., DLL/vendor chunks).
|
||||
internal class ConditionalProxyMiddleware {
|
||||
private RequestDelegate next;
|
||||
private ConditionalProxyMiddlewareOptions options;
|
||||
private HttpClient httpClient;
|
||||
private string pathPrefix;
|
||||
/// <summary>
|
||||
/// Based on https://github.com/aspnet/Proxy/blob/dev/src/Microsoft.AspNetCore.Proxy/ProxyMiddleware.cs
|
||||
/// Differs in that, if the proxied request returns a 404, we pass through to the next middleware in the chain
|
||||
/// This is useful for Webpack middleware, because it lets you fall back on prebuilt files on disk for
|
||||
/// chunks not exposed by the current Webpack config (e.g., DLL/vendor chunks).
|
||||
/// </summary>
|
||||
internal class ConditionalProxyMiddleware
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ConditionalProxyMiddlewareOptions _options;
|
||||
private readonly string _pathPrefix;
|
||||
|
||||
public ConditionalProxyMiddleware(RequestDelegate next, string pathPrefix, ConditionalProxyMiddlewareOptions options)
|
||||
public ConditionalProxyMiddleware(
|
||||
RequestDelegate next,
|
||||
string pathPrefix,
|
||||
ConditionalProxyMiddlewareOptions options)
|
||||
{
|
||||
this.next = next;
|
||||
this.pathPrefix = pathPrefix;
|
||||
this.options = options;
|
||||
this.httpClient = new HttpClient(new HttpClientHandler());
|
||||
_next = next;
|
||||
_pathPrefix = pathPrefix;
|
||||
_options = options;
|
||||
_httpClient = new HttpClient(new HttpClientHandler());
|
||||
}
|
||||
|
||||
|
||||
public async Task Invoke(HttpContext context)
|
||||
{
|
||||
if (context.Request.Path.StartsWithSegments(this.pathPrefix)) {
|
||||
if (context.Request.Path.StartsWithSegments(_pathPrefix))
|
||||
{
|
||||
var didProxyRequest = await PerformProxyRequest(context);
|
||||
if (didProxyRequest) {
|
||||
if (didProxyRequest)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Not a request we can proxy
|
||||
await this.next.Invoke(context);
|
||||
await _next.Invoke(context);
|
||||
}
|
||||
|
||||
private async Task<bool> PerformProxyRequest(HttpContext context) {
|
||||
|
||||
private async Task<bool> PerformProxyRequest(HttpContext context)
|
||||
{
|
||||
var requestMessage = new HttpRequestMessage();
|
||||
|
||||
// Copy the request headers
|
||||
foreach (var header in context.Request.Headers) {
|
||||
if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null) {
|
||||
foreach (var header in context.Request.Headers)
|
||||
{
|
||||
if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()))
|
||||
{
|
||||
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
requestMessage.Headers.Host = options.Host + ":" + options.Port;
|
||||
var uriString = $"{options.Scheme}://{options.Host}:{options.Port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
|
||||
|
||||
requestMessage.Headers.Host = _options.Host + ":" + _options.Port;
|
||||
var uriString =
|
||||
$"{_options.Scheme}://{_options.Host}:{_options.Port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
|
||||
requestMessage.RequestUri = new Uri(uriString);
|
||||
requestMessage.Method = new HttpMethod(context.Request.Method);
|
||||
|
||||
using (var responseMessage = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted)) {
|
||||
if (responseMessage.StatusCode == HttpStatusCode.NotFound) {
|
||||
using (
|
||||
var responseMessage =
|
||||
await
|
||||
_httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead,
|
||||
context.RequestAborted))
|
||||
{
|
||||
if (responseMessage.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
// Let some other middleware handle this
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// We can handle this
|
||||
context.Response.StatusCode = (int)responseMessage.StatusCode;
|
||||
foreach (var header in responseMessage.Headers) {
|
||||
context.Response.StatusCode = (int) responseMessage.StatusCode;
|
||||
foreach (var header in responseMessage.Headers)
|
||||
{
|
||||
context.Response.Headers[header.Key] = header.Value.ToArray();
|
||||
}
|
||||
|
||||
foreach (var header in responseMessage.Content.Headers) {
|
||||
foreach (var header in responseMessage.Content.Headers)
|
||||
{
|
||||
context.Response.Headers[header.Key] = header.Value.ToArray();
|
||||
}
|
||||
|
||||
@@ -77,16 +97,4 @@ namespace Microsoft.AspNetCore.SpaServices.Webpack
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class ConditionalProxyMiddlewareOptions {
|
||||
public string Scheme { get; private set; }
|
||||
public string Host { get; private set; }
|
||||
public string Port { get; private set; }
|
||||
|
||||
public ConditionalProxyMiddlewareOptions(string scheme, string host, string port) {
|
||||
this.Scheme = scheme;
|
||||
this.Host = host;
|
||||
this.Port = port;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace Microsoft.AspNetCore.SpaServices.Webpack
|
||||
{
|
||||
internal class ConditionalProxyMiddlewareOptions
|
||||
{
|
||||
public ConditionalProxyMiddlewareOptions(string scheme, string host, string port)
|
||||
{
|
||||
Scheme = scheme;
|
||||
Host = host;
|
||||
Port = port;
|
||||
}
|
||||
|
||||
public string Scheme { get; }
|
||||
public string Host { get; }
|
||||
public string Port { get; }
|
||||
}
|
||||
}
|
||||
@@ -9,22 +9,31 @@ using Microsoft.Extensions.PlatformAbstractions;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
// Putting in this namespace so it's always available whenever MapRoute is
|
||||
|
||||
namespace Microsoft.AspNetCore.Builder
|
||||
{
|
||||
public static class WebpackDevMiddleware
|
||||
{
|
||||
const string WebpackDevMiddlewareScheme = "http";
|
||||
const string WebpackDevMiddlewareHostname = "localhost";
|
||||
const string WebpackHotMiddlewareEndpoint = "/__webpack_hmr";
|
||||
const string DefaultConfigFile = "webpack.config.js";
|
||||
private const string WebpackDevMiddlewareScheme = "http";
|
||||
private const string WebpackDevMiddlewareHostname = "localhost";
|
||||
private const string WebpackHotMiddlewareEndpoint = "/__webpack_hmr";
|
||||
private const string DefaultConfigFile = "webpack.config.js";
|
||||
|
||||
public static void UseWebpackDevMiddleware(this IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options = null) {
|
||||
// Validate options
|
||||
if (options == null) {
|
||||
public static void UseWebpackDevMiddleware(
|
||||
this IApplicationBuilder appBuilder,
|
||||
WebpackDevMiddlewareOptions options = null)
|
||||
{
|
||||
// Prepare options
|
||||
if (options == null)
|
||||
{
|
||||
options = new WebpackDevMiddlewareOptions();
|
||||
}
|
||||
if (options.ReactHotModuleReplacement && !options.HotModuleReplacement) {
|
||||
throw new ArgumentException("To enable ReactHotModuleReplacement, you must also enable HotModuleReplacement.");
|
||||
|
||||
// Validate options
|
||||
if (options.ReactHotModuleReplacement && !options.HotModuleReplacement)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
"To enable ReactHotModuleReplacement, you must also enable HotModuleReplacement.");
|
||||
}
|
||||
|
||||
// Unlike other consumers of NodeServices, WebpackDevMiddleware dosen't share Node instances, nor does it
|
||||
@@ -32,44 +41,55 @@ namespace Microsoft.AspNetCore.Builder
|
||||
// because it must *not* restart when files change (if it did, you'd lose all the benefits of Webpack
|
||||
// middleware). And since this is a dev-time-only feature, it doesn't matter if the default transport isn't
|
||||
// as fast as some theoretical future alternative.
|
||||
var hostEnv = (IHostingEnvironment)appBuilder.ApplicationServices.GetService(typeof (IHostingEnvironment));
|
||||
var nodeServices = Configuration.CreateNodeServices(new NodeServicesOptions {
|
||||
var hostEnv = (IHostingEnvironment)appBuilder.ApplicationServices.GetService(typeof(IHostingEnvironment));
|
||||
var nodeServices = Configuration.CreateNodeServices(new NodeServicesOptions
|
||||
{
|
||||
HostingModel = NodeHostingModel.Http,
|
||||
ProjectPath = hostEnv.ContentRootPath,
|
||||
WatchFileExtensions = new string[] {} // Don't watch anything
|
||||
WatchFileExtensions = new string[] { } // Don't watch anything
|
||||
});
|
||||
|
||||
// Get a filename matching the middleware Node script
|
||||
var script = EmbeddedResourceReader.Read(typeof (WebpackDevMiddleware), "/Content/Node/webpack-dev-middleware.js");
|
||||
var script = EmbeddedResourceReader.Read(typeof(WebpackDevMiddleware),
|
||||
"/Content/Node/webpack-dev-middleware.js");
|
||||
var nodeScript = new StringAsTempFile(script); // Will be cleaned up on process exit
|
||||
|
||||
// Tell Node to start the server hosting webpack-dev-middleware
|
||||
var devServerOptions = new {
|
||||
var devServerOptions = new
|
||||
{
|
||||
webpackConfigPath = Path.Combine(hostEnv.ContentRootPath, options.ConfigFile ?? DefaultConfigFile),
|
||||
suppliedOptions = options
|
||||
};
|
||||
var devServerInfo = nodeServices.InvokeExport<WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer", JsonConvert.SerializeObject(devServerOptions)).Result;
|
||||
var devServerInfo =
|
||||
nodeServices.InvokeExport<WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer",
|
||||
JsonConvert.SerializeObject(devServerOptions)).Result;
|
||||
|
||||
// Proxy the corresponding requests through ASP.NET and into the Node listener
|
||||
var proxyOptions = new ConditionalProxyMiddlewareOptions(WebpackDevMiddlewareScheme, WebpackDevMiddlewareHostname, devServerInfo.Port.ToString());
|
||||
var proxyOptions = new ConditionalProxyMiddlewareOptions(WebpackDevMiddlewareScheme,
|
||||
WebpackDevMiddlewareHostname, devServerInfo.Port.ToString());
|
||||
appBuilder.UseMiddleware<ConditionalProxyMiddleware>(devServerInfo.PublicPath, proxyOptions);
|
||||
|
||||
// While it would be nice to proxy the /__webpack_hmr requests too, these return an EventStream,
|
||||
// and the Microsoft.AspNetCore.Proxy code doesn't handle that entirely - it throws an exception after
|
||||
// a while. So, just serve a 302 for those.
|
||||
appBuilder.Map(WebpackHotMiddlewareEndpoint, builder => {
|
||||
builder.Use(next => async ctx => {
|
||||
ctx.Response.Redirect($"{ WebpackDevMiddlewareScheme }://{ WebpackDevMiddlewareHostname }:{ devServerInfo.Port.ToString() }{ WebpackHotMiddlewareEndpoint }");
|
||||
appBuilder.Map(WebpackHotMiddlewareEndpoint, builder =>
|
||||
{
|
||||
builder.Use(next => async ctx =>
|
||||
{
|
||||
ctx.Response.Redirect(
|
||||
$"{WebpackDevMiddlewareScheme}://{WebpackDevMiddlewareHostname}:{devServerInfo.Port.ToString()}{WebpackHotMiddlewareEndpoint}");
|
||||
await Task.Yield();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#pragma warning disable CS0649
|
||||
class WebpackDevServerInfo {
|
||||
public int Port;
|
||||
public string PublicPath;
|
||||
#pragma warning disable CS0649
|
||||
class WebpackDevServerInfo
|
||||
{
|
||||
public int Port { get; set; }
|
||||
public string PublicPath { get; set; }
|
||||
}
|
||||
#pragma warning restore CS0649
|
||||
}
|
||||
#pragma warning restore CS0649
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
namespace Microsoft.AspNetCore.SpaServices.Webpack {
|
||||
public class WebpackDevMiddlewareOptions {
|
||||
namespace Microsoft.AspNetCore.SpaServices.Webpack
|
||||
{
|
||||
public class WebpackDevMiddlewareOptions
|
||||
{
|
||||
public bool HotModuleReplacement { get; set; }
|
||||
public bool ReactHotModuleReplacement { get; set; }
|
||||
public string ConfigFile { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user