Blazor WebAssembly 环境变量

Blazor WebAssembly Environment Variables

我目前正在开发 .NET Standard 2.1 Blazor WebAssembly 应用程序。 我尝试根据环境变量包含或排除样式表。

在 .NET Core 中通常有环境标签助手,如下例所示:

<environment include="Development">
    <link rel="stylesheet" href="css/style.css" type="text/css" />
</environment>

<environment exclude="Development">
    <link rel="stylesheet" href="css/style.min.css" type="text/css" />
</environment>

这在 Blazor Server 应用程序中工作得很好,但在 Blazor WASm 中却不行,因为这是客户端代码。

因此我尝试根据Blazor WebAssembly中的环境变量找到include/exclude样式表的良好解决方案。

我目前的方法是使用 JSInterop 从我的 Blazor WASm Program.cs 文件中调用 JavaScript 辅助方法,并根据环境变量删除样式表:

await jsInterop.InvokeVoidAsync("helpers.setup", "Development");

我的 JavaScript 在客户端上是这样的:

window.helpers = {
    setup: (environment) => {

        if (environment === "Development") {
            // remove production styles
        }

        if (environment !== "Development") {
            // remove development styles
        }
    }
};

这个解决方案的问题是,我想将我的样式放入我的头文件并将它们分组到一个 <section> 元素或类似的东西中 - 这在有效的 HTML5 中不起作用。

您如何处理 Blazor WebAssembly 中的 Development/Production 环境?

如何根据项目设置 (launchsettings.json) 中设置的环境变量排除或包含特定 CSS 文件?

免责声明:

这只是我尝试过的似乎有效的方法。我找不到任何支持这样做的文档,也找不到任何说不要这样做的内容。如果有任何官方文档,请告诉我。

documentation状态:

When running an app locally, the environment defaults to Development. When the app is published, the environment defaults to Production.

进一步提到如何通过将文件发布到 IIS 时生成的 web.config 设置环境。 还有对 Use multiple environments in ASP.NET Core. and Host and deploy ASP.NET Core Blazor WebAssembly

的引用

然而这就是我所做的。

查看由new web assembly项目模板生成的Program.cs文件,builder是由WebAssemblyHostBuilder.CreateDefault(args);创建的必须意味着所有 default 服务必须已经在服务容器中注册。

这将包括 IWebAssemblyHostEnvironment 配置服务。

下一行 builder.RootComponents.Add<App>("app");添加App <app></app> root component index.html 文件.

那么,为什么不尝试创建一个 Head <head></head> component 看看会发生什么。

我创建了一个 Head razor 组件并将其命名为 Head.razor,其中包含通常位于 <head></head> 标签之间的所有 html

@using Microsoft.AspNetCore.Components.WebAssembly.Hosting
@inject IWebAssemblyHostEnvironment hostEnv

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />

@*Check the environment value*@
@if (hostEnv.IsDevelopment())
{
    <title>BlazorWasmApp - In Debug</title>
    <link href="css/debug.css" rel="stylesheet" />
}
else
{
    <title>BlazorWasmApp - Not Debug</title>
    <link href="css/live.css" rel="stylesheet" />
}

@code {}

因为它是一个 组件 你可以注入 IWebAssemblyHostEnvironment 并检查 .IsDevelopment(),.IsProduction() 等..扩展方法值。

我在 index.html 文件中保留了原始 <head> 标签,因为 <head>...gets overwritten...</head> 的内容似乎已被完全覆盖。

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>BlazorWasmApp</title>
    <base href="/" />
    <link href="css/app.css" rel="stylesheet" />
</head>
<body>
    <app>Loading...</app>    
...
...

同时在 <head> 标签中保留对 cs/app.css 文件的引用不会改变应用程序 正在加载时的外观....

我将 Head class 注册到 Program class 中的 builder.RootComponents 集合。

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);            
    builder.RootComponents.Add<App>("app");

    //Add the Head to root components
    builder.RootComponents.Add<Head>("head");            
            
    builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });           
    await builder.Build().RunAsync();
}

我添加了 2 个 css 文件到 wwwroot/css 文件夹 debug.csslive.css 每个都包含一个简单的 body { background-color:*red or blue* } 样式。

launchSettings.json 文件的配置文件部分,将 IIS Express : environmentVariables : ASPNETCORE_ENVIRONMENT 设置为“Development”,将 [YourAppName] : environmentVariables : ASPNETCORE_ENVIRONMENT 设置为“ 生产”。

"profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}"
    },
    "BlazorWasmApp": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      },
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}"
    }
  }

使用 IIS Express 配置文件(开发)启动应用程序时,背景为 红色,使用 [=92] 启动应用程序时=][YourAppName] 配置文件(生产)背景为 blue.

使用开发人员工具查看 <head></head> 标签时,根据环境,head 标签的内容包含 css 引用。

IIS 快递:

BlazorWasmApp(我的应用配置文件):