Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recompile .razor files on save for Blazor WASM

Is there a way to make Blazor Webassembly recompile .razor files when they're changed/updated and then saved? I'm used to this happening both in traditional ASP.NET Core MVC razor views as well as client-side frameworks like Angular. In ASP.NET Core MVC >3.0, something like services.AddRazorPages().AddRazorRuntimeCompilation(); would do the trick, but nothing exists for Blazor that I could find.

It's annoying when I need to stop the entire application and restart it to see the latest changes. By default the Main method for a new Blazor application looks like

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

            builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

            await builder.Build().RunAsync();
        }

What am I missing here? Is Blazor WASM just not there yet? I'm open to something a little hacky like dotnet watch dotnet build if that's a solution.

like image 620
Ben Sampica Avatar asked May 31 '20 16:05

Ben Sampica


3 Answers

As of .NET 5.0 and VS 16.8.1 it doesn't look like there is a built in HMR like you would find with an Angular or React project, where you can change code and have it refresh the browser.

According to the info I have found, this functionality is slated for .NET 6 but there is workaround to get this working, it is a little cumbersome but it does work.

If you run the .NET project using dotnet watch --project "{PathToServer}/{YourServerProject}.csproj" run instead of starting the debug or pressing F5 it will watch for any changes in the project's files including the .razor files and recompile them.

As of right now the browser will display a message saying that it lost connection to the server and doesn't seem to reestablish a connection. You are required to refresh the browser manually and any changes will be displayed but you will lose any application state.

Best that they have right now, see this thread for more info

like image 146
Andy Braham Avatar answered Oct 17 '22 04:10

Andy Braham


Support is being added in .net 6: https://www.telerik.com/blogs/instant-feedback-is-here-introducing-hot-reload-in-dotnet-6

like image 33
Cine Avatar answered Oct 17 '22 04:10

Cine


Try this simple solution:-

Run the project with Ctrl + F5 (without the debugger) instead of F5 and on IIS express. Once .cs and .razor files are changed and saved across the solution, they are automatically rebuilt and the app restarted so that the changes can be seen by simply refreshing the browser.

like image 23
Faisal Mushtaq Avatar answered Oct 17 '22 04:10

Faisal Mushtaq