Skip to content

Instantly share code, notes, and snippets.

@alexeyzimarev
Created January 27, 2019 13:26
Show Gist options
  • Save alexeyzimarev/deda49dc8faf26b0d0978610d91b5c41 to your computer and use it in GitHub Desktop.
Save alexeyzimarev/deda49dc8faf26b0d0978610d91b5c41 to your computer and use it in GitHub Desktop.
Perspective Vue CLI middleware that uses the generic npm middleware
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.SpaServices;
using Microsoft.AspNetCore.SpaServices.Npm;
namespace ASP.NETCoreWebApplication
{
/// <summary>
/// Extension methods for enabling React development server middleware support.
/// </summary>
public static class VueDevelopmentServerMiddlewareExtensions
{
/// <summary>
/// Handles requests by passing them through to an instance of the Vue CLI server.
/// This means you can always serve up-to-date CLI-built resources without having
/// to run the Vue CLI server manually.
///
/// This feature should only be used in development. For production deployments, be
/// sure not to enable the Vue CLI server.
/// </summary>
/// <param name="spaBuilder">The <see cref="ISpaBuilder"/>.</param>
/// <param name="npmScript">The name of the script in your package.json file that launches the Vue CLI server.</param>
public static void UseVueDevelopmentServer(
this ISpaBuilder spaBuilder,
string npmScript)
{
if (spaBuilder == null)
{
throw new ArgumentNullException(nameof(spaBuilder));
}
var spaOptions = spaBuilder.Options;
if (string.IsNullOrEmpty(spaOptions.SourcePath))
{
throw new InvalidOperationException(
$"To use {nameof(UseVueDevelopmentServer)}, you must supply a non-empty value for the {nameof(SpaOptions.SourcePath)} property of {nameof(SpaOptions)} when calling {nameof(SpaApplicationBuilderExtensions.UseSpa)}.");
}
VueDevelopmentServerMiddleware.Attach(spaBuilder, npmScript);
}
}
internal static class VueDevelopmentServerMiddleware
{
private static TimeSpan
RegexMatchTimeout =
TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine
public static void Attach(
ISpaBuilder spaBuilder,
string npmScriptName)
{
NpmMiddleware.Attach(spaBuilder, npmScriptName, port => null, EnvVars,
new Regex("Starting development server", RegexOptions.None, RegexMatchTimeout),
(match, port) => new UriBuilder("http", "localhost", port).Uri);
IDictionary<string, string> EnvVars(int portNumber) =>
new Dictionary<string, string>
{
{"PORT", portNumber.ToString()},
{
"BROWSER", "none"
} // We don't want Vie CLI to open its own extra browser window pointing to the internal dev server port
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment