javascriptcomponentsblazorinterop

How to reference local JS modules in Blazor components?


On Dotnetconf two weeks ago I heard it is now possible to include local Javascript files in Blazor components. That sounds very interesting. I guess the approach is still to use JSIniterop and reference the module file.

BUT how do you reference the JS file ??? I have tried all possible creative variants but so far without success.

I am surprised to Google everywhere but find no guides or sample yet on this. All hints are appreciated.


Solution

  • Given a ComponentLibrary.Blazor project and a component named MyComponent.razor in the Components folder. You can include the collocated JavaScript files by creating a JavaScript code behind file MyComponent.razor.js and importing the file with the correct path, ./_content/ComponentLibrary.Blazor/Components/MyComponent.razor.js.

    MyComponent.razor

    <div @ref="_elementReference">Hello world!</div>
    

    MyComponent.razor.cs:

    public partial class MyComponent {
        private IJSObjectReference? _collocatedJs;
        private ElementReference _elementReference;
    
        [Inject]
        public required IJSRuntime JsRuntime { get; set; }
    
        protected override async Task OnAfterRenderAsync(bool firstRender) {
            await base.OnAfterRenderAsync(firstRender);
            _collocatedJs ??= await JsRuntime.InvokeAsync<IJSObjectReference>(
                "import",
                "./_content/ComponentLibrary.Blazor/Components/MyComponent.razor.js");
        }
    
        public async Task InvokeJavaScriptFunction() {
            if (_collocatedJs != null) {
                await _collocatedJs.InvokeVoidAsync("doJavaScriptWork", _elementReference);
            }
        }
    }
    

    MyComponent.razor.js

    export function doJavaScriptWork(elementReference) {
        console.log(elementReference);
    }