Blazor Webassembly Load Different Scripts For Specific Environment
I'm currently working on a .NET Standard 2.1 Blazor WebAssembly application. I try to include or exclude JavaScript files in my index.html according to an environment variable. The
Solution 1:
Simply copy your index.html code in a .cshtml (named BlazorApp.cshtml in the following sample) in your server project and fallback to this page.
publicvoidConfigure(IApplicationBuilder app)
{
...
app.UseEndpoints(endpoints =>
{
...
endpoints.MapFallbackToPage("/BlazorApp");
}
}
And update the code with <environment>
tags for your conveniance.
Solution 2:
Please check the solution in this answer (same question as you linked above) and that seems to work.
Basically the workaround is to use this in a new component called Head.razor
as per the solution:
@inject IWebAssemblyHostEnvironment hostEnv
@if (hostEnv.IsDevelopment())
{
<title>BlazorWasmApp - In Debug</title><linkhref="css/debug.css" />
}
else
{
<title>BlazorWasmApp - Not Debug</title><linkhref="css/live.css" />
}
New Head.razor
component:
publicstaticasync 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();
}
Solution 3:
I wanted to add Tailwind CDN script tag just during development. I ended up using the solution below:
index.html
<scriptsrc="_framework/blazor.webassembly.js"></script><script>// If localhost, add tailwind CDN (or any other script that you want)if (window.location.hostname == 'localhost') {
var customScript = document.createElement('script');
customScript.setAttribute('src', 'https://cdn.tailwindcss.com');
document.head.appendChild(customScript);
}
</script>
Post a Comment for "Blazor Webassembly Load Different Scripts For Specific Environment"