最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to reference local JS modules in Blazor components? - Stack Overflow

programmeradmin1浏览0评论

On Dotnetconf two weeks ago I heard it is now possible to include local Javascript files in Blazor ponents. 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.

On Dotnetconf two weeks ago I heard it is now possible to include local Javascript files in Blazor ponents. 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.

Share Improve this question asked Nov 19, 2021 at 15:22 Jakob LithnerJakob Lithner 4,4267 gold badges41 silver badges62 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

You can create .js code file next to .razor.cs file and load that file in runtime. It's described here. Also I found presentation of this feature here and github repo here.

Let's say that you have ComponentA with ComponentA.razor, ComponentA.razor.cs and ComponentA.razor.js files in Pages folder. You can load this module during ponent's initialization like so:

[Inject]
public IJSRuntime JS { get; set; }

private IJSObjectReference module { get; set; }

protected override async Task OnInitializedAsync()
{
    module = await JS.InvokeAsync<IJSObjectReference>("import", "./Pages/ComponentA.razor.js");
}

But if your ponent is defined in a ponent library project then you have to use different file path. For example if your project is named AppComponents then this path would be ./_content/AppComponents/ComponentA.razor.js.

Given a ComponentLibrary.Blazor project and a ponent 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);
}

The question is regarding Blazor, but I see answers mentioning .razor.cs files, which exist in other ASP.NET apps but not in Blazor, you only have .razor files. I found an example here Load a script from an external JavaScript file (.js) collocated with a ponent but found the example a little hard to follow because it's not totally concrete, and when I did it as shown my app couldn't find the JavaScript file. So here is my explanation going off that example. I suggest following it exactly and then making modifications as desired to suite your needs.

  1. Under wwwroot/bootstrap add a file named "JsCollocation1.js".
  2. Add the following JavaScript code to the file:
function showPrompt1(message) {
    return prompt(message, 'Type your name here');
}
  1. In your web project, open the file App.razor. You should see a line of code like this
<script src="_framework/blazor.web.js"></script>

Below that line add this line:

<script src="./bootstrap/JsCollocation1.js"></script>
  1. In your .razor page add the following code:
@inject IJSRuntime JS

<button @onclick="ShowPrompt">Call showPrompt1</button>

@if (!string.IsNullOrEmpty(result))
{
    <p>
        Hello @result!
    </p>
}

@code {
    private string? result;

    public async void ShowPrompt()
    {
        result = await JS.InvokeAsync<string>(
            "showPrompt1", "What's your name?");
        StateHasChanged();
    }
}

With that you should be able to run your app, click on the button and then see the prompt pop up.

发布评论

评论列表(0)

  1. 暂无评论