Notyf View Component Not Working When Using Environment Tag

Viewed 54

In my dotnet 5 MVC web application, I'm using THIS ToastNotification library for showing notifications. It's working good since long. As documentation says, it requires following line in _Layout file

@await Component.InvokeAsync("Notyf")

So a part of this file looks something like:

<script src="~/js/site.js" asp-append-version="true"></script>
<script src="~/js/controls.js" asp-append-version="true"></script>

@await Component.InvokeAsync("Notyf")
@await RenderSectionAsync("Scripts", required: false)

Now I wanted to minify the js files mentioned in first two lines. So I created minified bundle for the two files, hence the above sections now looks like:

<environment names="Development">
    <script src="~/js/site.js" asp-append-version="true"></script>
    <script src="~/js/controls.js" asp-append-version="true"></script>
</environment>

<environment names="Staging,Production">
    <script src="~/js/_Bundles/common.min.js" asp-append-version="true"></script>
</environment>

@await Component.InvokeAsync("Notyf")
@await RenderSectionAsync("Scripts", required: false)

After this change:

  1. If I set environment to be Development, then all works correctly as before.
  2. If I set environment to be Production, the Notyf component doesn't load correctly. Apparantly it seems like it is being used even before it is available. I get the following error on loading page

enter image description here

enter image description here

Any Idea why is this happening? I did not touch this line at all. Any solution or alternate approach will be appreciated.

1 Answers

You need to enable StaticWebAssetsFileProvider manually in a not "Development" environment:

// Program.cs
...
public class Program
{
  ...
  public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .ConfigureWebHostDefaults(webBuilder =>
      {
        webBuilder.UseStartup<Startup>();

        // Add this "ConfigureAppConfiguration" method calling.
        webBuilder.ConfigureAppConfiguration((ctx, cb) =>
        {
          //    Please specify the condition that is true only when
          //    the application is running on your development environment.
          //    Notice that excludes the case that the environment is "Development".
          if (!ctx.HostingEnvironment.IsDevelopment() &&
               /* your prefer condition*/)
          {
            //    This call inserts "StaticWebAssetsFileProvider" into
            //    the static file middleware.
            StaticWebAssetsLoader.UseStaticWebAssets(
              ctx.HostingEnvironment, 
              ctx.Configuration);
          }
        });
        ...
Related