asp.net-coreblazor

Blazor web app couldn't find js function in external js file


Here is my repo with fresh template reproducing the issue. On the counter page in the button click handler added JS interop call which should normally invoke js function named "sayHello()" locatedn in wwwroot/JSFile.js

https://github.com/konst-sh/JSFunctionNotFound/tree/master

I keep getting this error in browser console:

Microsoft.JSInterop.JSException: Could not find 'sayHello' ('sayHello' was undefined).

The script reference seem to be located properly in App.razor file inside the tag:

<script src="JSFile.js"></script>

if same function is added to the Counter.razor page inside the script tag it works as expected

<script>
function sayHello() {
    console.log("Hello from JSFile");
}
</script>

Solution

  • You can remove export in JSFile.js ,I remove it and it works well like this: enter image description here

    If you want use export ,you should use JSHost.ImportAsync,you can learn more from this website:https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/import-export-interop?view=aspnetcore-8.0