ASP.NET Core 非 Spa 项目中的 Webpack 服务(或另一个 npm 脚本)

问题描述 投票:0回答:1

我正在前端部分开发一个ASP.NET Core非spa项目,该项目与后端混合在一起。我需要的是,当我构建和启动项目时,启动 webpack-dev-server (或其他 npm 脚本,它将监视)。我将只提供 js、css、资源,但不提供 html,因为有 Razor 和

.cshtml

现在我正在使用:

app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";                 
                spa.UseReactDevelopmentServer(npmScript: "start");
            });

为了解决我的问题,它以某种方式起作用,但我不明白为什么我需要使用它。

为什么没有

useDevelopmentServer
useNodeCommand
之类的东西?

我只需要在非水疗项目中利用现代开发的所有可能性,然后我们的客户就会决定转向水疗中心。

当然,我可以从终端手动启动我的npm(或yarn或其他任何东西),但我需要流程自动化,因为很难解释我们的后端程序如何做到这一点,而且因为它很方便。

asp.net asp.net-core webpack single-page-application multi-page-application
1个回答
0
投票

我们可以使用中间件来实现它,并且我们应该让这个npm脚本只运行一次。这是我的示例中间件。

NpmMiddleware.cs

public class NpmMiddleware
{
    private static bool _npmScriptStarted = false;
    private readonly RequestDelegate _next;
    private readonly string _sourcePath;
    private readonly string _npmScript;

    public NpmMiddleware(RequestDelegate next, string sourcePath, string npmScript)
    {
        _next = next;
        _sourcePath = sourcePath;
        _npmScript = npmScript;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (!_npmScriptStarted)
        {
            var isDevelopment = string.Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), "Development", StringComparison.OrdinalIgnoreCase);
            
            if (isDevelopment)
            {
                var npmScriptProcess = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "npm",
                        Arguments = $"run {_npmScript}",
                        RedirectStandardError = true,
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true,
                        UseShellExecute = false,
                        WorkingDirectory = _sourcePath
                    }
                };

                npmScriptProcess.Start();
                _npmScriptStarted = true;
            }
        }

        // Call the next delegate/middleware in the pipeline
        await _next(context);
    }
}
public static class NpmMiddlewareExtensions
{
    public static IApplicationBuilder UseNpmScript(this IApplicationBuilder builder, string sourcePath, string npmScript)
    {
        return builder.UseMiddleware<NpmMiddleware>(sourcePath, npmScript);
    }
}

并在 Program.cs(或startup.cs 文件,如果有的话)文件中使用它。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... other middlewares ...

    app.UseNpmScript("ClientApp", "start");

    // ... remaining configuration ...
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.