asp.net core mvc 中间件之WebpackDevMiddleware

本文涉及的产品
云原生网关 MSE Higress,422元/月
注册配置 MSE Nacos/ZooKeeper,118元/月
性能测试 PTS,5000VUM额度
简介: asp.net core mvc 中间件之WebpackDevMiddlewareWebpackDevMiddleware中间件主要用于开发SPA应用,启用Webpack,增强网页开发体验。好吧,你想用来干嘛就干嘛,这次主要是通过学习该中间件,学习如何在core中启用Webpack支持通过上上篇asp.

asp.net core mvc 中间件之WebpackDevMiddleware

  • WebpackDevMiddleware中间件主要用于开发SPA应用,启用Webpack,增强网页开发体验。好吧,你想用来干嘛就干嘛,这次主要是通过学习该中间件,学习如何在core中启用Webpack支持
  • 通过上上篇asp.net core mvc 管道之中间件,大致可以了解中间件是什么东西,现在就以中间件为单位,一个一个点学习各种中间件,了解并掌握,最后学会自己写中间件
  • 该中间件源码

说明

WebpackDevMiddleware

  • Enables Webpack dev middleware support. This hosts an instance of the Webpack compiler in memory
    in your application so that you can always serve up-to-date Webpack-built resources without having
    to run the compiler manually. Since the Webpack compiler instance is retained in memory, incremental
    compilation is vastly faster that re-running the compiler from scratch.
    Incoming requests that match Webpack-built files will be handled by returning the Webpack compiler
    output directly, regardless of files on disk. If compilation is in progress when the request arrives,
    the response will pause until updated compiler output is ready.

  • 大概意思是Webpack编译器实例存在于内存,始终提供最新编译的资源,增量编译比重新编译速度要快得多。任何请求Webpack编译后的文件,都原样返回,如果请求到达时编译没完成,响应将暂停,直到编译完成,输出准备就绪

NodeServices

  • Unlike other consumers of NodeServices, WebpackDevMiddleware dosen't share Node instances, nor does it
    use your DI configuration. It's important for WebpackDevMiddleware to have its own private Node instance
    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.

  • WebpackDevMiddleware不共享Node实例,也不共享使用的DI配置。因为文件改变时Node服务不能重启。这是个开发时使用的功能,所以传输速度可能不会很快

分析

  • 创建Node实例
var nodeServicesOptions = new NodeServicesOptions(appBuilder.ApplicationServices);
var nodeServices = NodeServicesFactory.CreateNodeServices(nodeServicesOptions);
  • 创建devServerOptions,包含设置webpack.config.js的路径以及整合在Stratup.cs的设置、模块热加载断点等。这些设置需要传到Nodeaspnet-webpack模块,如果是自定义的模块,那么参数也是自己定义啦
var devServerOptions = new
{
    webpackConfigPath = Path.Combine(nodeServicesOptions.ProjectPath, options.ConfigFile ?? DefaultConfigFile),
    suppliedOptions = options,
    understandsMultiplePublicPaths = true,
    hotModuleReplacementEndpointUrl = hmrEndpoint
};
  • 下面是通过nodeServices,执行指定aspnet-webpack模块里面的方法并得到结果。参数分别是模块文件路径、要调用的方法、传递的参数。传递给js模块的参数先序列成json字符串,模块接收参数后再反序列化成对象
var devServerInfo =
    nodeServices.InvokeExportAsync<WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer",
        JsonConvert.SerializeObject(devServerOptions, jsonSerializerSettings)).Result;
  • 返回结果是Webpack编译之后的输出目录,循环输出目录,添加请求代理,代理到所有输出目录。超时时间100s, /__webpack_hmr无限超时
  • 代理源码
foreach (var publicPath in devServerInfo.PublicPaths)
{
    appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath + hmrEndpoint, devServerInfo.Port, Timeout.InfiniteTimeSpan);
    appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath, devServerInfo.Port, TimeSpan.FromSeconds(100));
}

// Note that this is hardcoded to make requests to "localhost" regardless of the hostname of the
// server as far as the client is concerned. This is because ConditionalProxyMiddlewareOptions is
// the one making the internal HTTP requests, and it's going to be to some port on this machine
// because aspnet-webpack hosts the dev server there. We can't use the hostname that the client
// sees, because that could be anything (e.g., some upstream load balancer) and we might not be
// able to make outbound requests to it from here.
// Also note that the webpack HMR service always uses HTTP, even if your app server uses HTTPS,
// because the HMR service has no need for HTTPS (the client doesn't see it directly - all traffic
// to it is proxied), and the HMR service couldn't use HTTPS anyway (in general it wouldn't have
// the necessary certificate).
var proxyOptions = new ConditionalProxyMiddlewareOptions(
    "http", "localhost", proxyToPort.ToString(), requestTimeout);
appBuilder.UseMiddleware<ConditionalProxyMiddleware>(publicPath, proxyOptions);

结果

  • 创建自己的中间件,自定义配置,运行Webpack服务,只需要创建Node实例,调用自己写的模块即可。模块根据传过来的配置运行服务即可
  • 关键方法
var nodeServicesOptions = new NodeServicesOptions(appBuilder.ApplicationServices); // node配置

var nodeServices = NodeServicesFactory.CreateNodeServices(nodeServicesOptions); // 创建node实例 

// dev服务配置
var devServerOptions = new
{
    webpackConfigPath = Path.Combine(nodeServicesOptions.ProjectPath, options.ConfigFile ?? DefaultConfigFile),
    suppliedOptions = options,
    understandsMultiplePublicPaths = true,
    hotModuleReplacementEndpointUrl = hmrEndpoint
};

// 调用js模块,运行dev服务,返回输出目录
var devServerInfo =
    nodeServices.InvokeExportAsync<WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer",
        JsonConvert.SerializeObject(devServerOptions, jsonSerializerSettings)).Result;

// 添加输出目录到代理
foreach (var publicPath in devServerInfo.PublicPaths)
{
    appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath + hmrEndpoint, devServerInfo.Port, Timeout.InfiniteTimeSpan);
    appBuilder.UseProxyToLocalWebpackDevMiddleware(publicPath, devServerInfo.Port, TimeSpan.FromSeconds(100));
}

private static void UseProxyToLocalWebpackDevMiddleware(this IApplicationBuilder appBuilder, string publicPath, int proxyToPort, TimeSpan requestTimeout)
{
    var proxyOptions = new ConditionalProxyMiddlewareOptions(
        "http", "localhost", proxyToPort.ToString(), requestTimeout);
    appBuilder.UseMiddleware<ConditionalProxyMiddleware>(publicPath, proxyOptions);
}

示例

  • 待更新...
用心做好每一件事,结果会给你最大的惊喜!
目录
相关文章
|
2月前
|
存储 开发框架 JSON
ASP.NET Core OData 9 正式发布
【10月更文挑战第8天】Microsoft 在 2024 年 8 月 30 日宣布推出 ASP.NET Core OData 9,此版本与 .NET 8 的 OData 库保持一致,改进了数据编码以符合 OData 规范,并放弃了对旧版 .NET Framework 的支持,仅支持 .NET 8 及更高版本。新版本引入了更快的 JSON 编写器 `System.Text.UTF8JsonWriter`,优化了内存使用和序列化速度。
|
18天前
|
开发框架 .NET C#
在 ASP.NET Core 中创建 gRPC 客户端和服务器
本文介绍了如何使用 gRPC 框架搭建一个简单的“Hello World”示例。首先创建了一个名为 GrpcDemo 的解决方案,其中包含一个 gRPC 服务端项目 GrpcServer 和一个客户端项目 GrpcClient。服务端通过定义 `greeter.proto` 文件中的服务和消息类型,实现了一个简单的问候服务 `GreeterService`。客户端则通过 gRPC 客户端库连接到服务端并调用其 `SayHello` 方法,展示了 gRPC 在 C# 中的基本使用方法。
29 5
在 ASP.NET Core 中创建 gRPC 客户端和服务器
|
8天前
|
开发框架 缓存 .NET
GraphQL 与 ASP.NET Core 集成:从入门到精通
本文详细介绍了如何在ASP.NET Core中集成GraphQL,包括安装必要的NuGet包、创建GraphQL Schema、配置GraphQL服务等步骤。同时,文章还探讨了常见问题及其解决方法,如处理复杂查询、错误处理、性能优化和实现认证授权等,旨在帮助开发者构建灵活且高效的API。
17 3
|
2月前
mcr.microsoft.com/dotnet/core/aspnet:2.1安装libgdiplus
mcr.microsoft.com/dotnet/core/aspnet:2.1安装libgdiplus
32 1
|
3月前
|
开发框架 监控 前端开发
在 ASP.NET Core Web API 中使用操作筛选器统一处理通用操作
【9月更文挑战第27天】操作筛选器是ASP.NET Core MVC和Web API中的一种过滤器,可在操作方法执行前后运行代码,适用于日志记录、性能监控和验证等场景。通过实现`IActionFilter`接口的`OnActionExecuting`和`OnActionExecuted`方法,可以统一处理日志、验证及异常。创建并注册自定义筛选器类,能提升代码的可维护性和复用性。
|
3月前
|
开发框架 .NET 中间件
ASP.NET Core Web 开发浅谈
本文介绍ASP.NET Core,一个轻量级、开源的跨平台框架,专为构建高性能Web应用设计。通过简单步骤,你将学会创建首个Web应用。文章还深入探讨了路由配置、依赖注入及安全性配置等常见问题,并提供了实用示例代码以助于理解与避免错误,帮助开发者更好地掌握ASP.NET Core的核心概念。
109 3
|
2月前
|
开发框架 JavaScript 前端开发
一个适用于 ASP.NET Core 的轻量级插件框架
一个适用于 ASP.NET Core 的轻量级插件框架
|
3月前
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
45 7
|
3月前
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
72 0
|
6月前
|
消息中间件 存储 中间件
【消息中间件】详解三大MQ:RabbitMQ、RocketMQ、Kafka
【消息中间件】详解三大MQ:RabbitMQ、RocketMQ、Kafka
1588 0

热门文章

最新文章