Blazor, the Razor Library, npm, and webpack are essential tools for front

Let me try to explain this clearly. I have a Blazor WebAssembly (WASM) project that is referencing a Razor library without any issues. The Razor library successfully compiles a JavaScript bundle using webpack. One of the components I am attempting to create has a simple function that returns the revision of a package (threejs) as a string.

Here's where the problem arises: Despite having everything set up correctly, when I attempt to call the function from the Blazor project, I consistently receive an error stating that the function does not exist.

Error

  • index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>Atom.Web.Client</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/app.css" rel="stylesheet" />
    <link href="Atom.Web.Client.styles.css" rel="stylesheet" />
</head>

<body>
    <div id="app">Loading...</div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">🗙</a>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>
    <script src="./_content/Atom.Web.Viewer.Components/js/atom.bundle.js"></script>
</body>

</html>
  • Webpack config
const path = require("path");

module.exports = {
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    },
    output: {
        path: path.resolve(__dirname, '../wwwroot/js'),
        filename: "atom.bundle.js",
        library: "Atom"
    }
};
  • the component code
private readonly Lazy<Task<IJSObjectReference>> moduleTask;

    public ThreeViewer(IJSRuntime jsRuntime)
    {
        moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>(
            "import", "./_content/Atom.Web.Viewer.Components/js/atom.bundle.js").AsTask());
    }


    public async ValueTask<string> GetRevision()
    {
        var module = await moduleTask.Value;
        var rev =  await module.InvokeAsync<string>("Atom.GetCurrentThreeRevision");
        return rev;
    }
  • the Program.cs
using Atom.Web.Client;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Atom.Web.Viewer.Components;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

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

await builder.Build().RunAsync();
  • the Index.razor
@inject IJSRuntime JSRuntime;
@inject ThreeViewer threeViewer;
@page "/"
@using Newtonsoft.Json

<PageTitle>Index</PageTitle>

@if(revisionMessage != string.Empty)
{
<h1>@revisionMessage</h1>
}

<SurveyPrompt Title="How is Blazor working for you?" />

@code {
string revisionMessage = string.Empty;
protected override async Task OnInitializedAsync()
{
revisionMessage = await JSRuntime.InvokeAsync<string>("Atom.GetCurrentThreeRevision");
var rev = await threeViewer.GetRevision();
}
}

The interesting part is, if I directly call the function using `revisionMessage` through JSRuntime, it works flawlessly. However, when attempting to call it from the component library, issues arise.

Any assistance would be greatly appreciated!

Answer â„–1

I have successfully resolved the issue on my own. I made the decision to eliminate the dynamic loading of the library within the Razor component and assumed that this library would be loaded in the main Blazor app.

public async Task<string> GetRevision()
        {
            return await JSRuntime.InvokeAsync<string>("Atom.GetCurrentThreeRevision");
        }

        public async Task<Scene> InitiateScene()
        {
            string text = JsonConvert.SerializeObject((object)new { Scene, ViewerSettings, Camera, OrbitControls }, SerializationHelper.GetSerializerSettings());
            return await JSRuntime.InvokeAsync<Scene>("Atom.InitiateScene");
        }

All other components remain unchanged for the most part.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing active className in nextjs: A step-by-step guide

I am a beginner with Nextjs and I am trying to implement a feature where the color of a nav-link changes when it is selected. I am currently using Nextjs+react-bootstrap in my project. This is how my Navbar component is structured: import React from " ...

Respond to adjustments in iframe height

I am currently working on a page with an embedded iframe. The height of the iframe may change dynamically while on the page. I am wondering if there is a way to adjust the height of the iframe based on its content. Even after trying to set the height at ...

The functionality to refresh an input field upon clicking a button is not functioning as expected

I am currently developing a small MVC.NET web application with user input functionality. The goal is to calculate and display the results in two input fields upon button click. However, I am facing an issue where the input fields remain empty after the but ...

Setting up Spectron

I attempted to install Spectron using the following command: npm install --save-dev spectron However, I encountered the following error message: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\P ...

Obtain the result of two "Synchronous" nested queries using Express and Mongoose

I need to fetch an array of elements structured like this: ApiResponse = [ {_id: 1, name: Mike, transactions: 5}, {_id: 2, name: Jhon, Transactions: 10} ] The user data is retrieved from a query on the "Users" schema, while the tr ...

The Node.js Twitter Bot encountered an issue: Twitter streaming request error 410 - something went wrong

After running the bot successfully for approximately 8 hours, I encountered an unexpected issue when trying to run it again: events.js:183 throw er; // Unhandled 'error' event ^Error: Bad Twitter streaming request: 410 at Object.exports.make ...

What is the best way to submit several files along with additional fields simultaneously using FormData?

I have a collection called pocketbase that consists of fields like name, image, and order. My goal is to upload all the images with unique names and in parallel using the power of FormData. Take a look at my code below: export default function AddPhotosAd ...

Having trouble with the form parsing not functioning properly

I have been utilizing Express.js along with the body-parser module for form parsing on the server. However, I am facing an issue where the content received appears as an empty object under res.body. This is how my app.js looks: var express = require("exp ...

Troubleshooting: Why is my express-fileupload failing to upload images

I'm currently working on implementing a feature that allows users to upload a profile image for their profiles. I have the form set up the way I want it, but I keep encountering an error that says TypeError: Cannot read property 'profilePicUpload ...

Angular.js unable to locate image 404 Error occurs

I am facing a small issue. I want to display icons from categories that I receive from my REST API. To achieve this, I am using AngularJS with REST API which provides me with the designed icons. However, I encountered an error in Firebug: "NetworkError: 4 ...

What are the best practices for preventing duplicate IDs in JavaScript-based web applications?

On my heavily JavaScript-based webpage, I have sections that consist of lists of HTML elements categorized as lists A and B. When the first item in list A (A1) is clicked, an action is triggered on the first item in list B (B1). To simplify the process, e ...

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

Running the Npm start command encounters an error

My terminal is showing the following error message: Q:\clone\node-cloudinary-instagram\node_modules\express\lib\router\route.js:202 throw new Error(msg); Error: Route.get() requires a callback function but go ...

The Distribution and Subscription of Meteor Collections

Today has been a challenging day for me. I have encountered several related topics while trying to solve my issue, but unfortunately, I haven't been able to fix it yet. Being relatively new to Meteor, I have removed autopublish and am not sure if I am ...

When dynamically loading content with ajax, dynamic content fails to function properly

Currently, I am attempting to incorporate dynamic content loading after the user logs in by utilizing $.ajax. Here is how it's being done: $.ajax({ url: "functions.php", type: "GET", data: login_info, datatype: 'html', a ...

Opencart: The Key to Your Website's Success

Quick question - I have a Java snippet that needs to be added to my OpenCart checkout page before the closing </body> tag. However, I cannot locate the </body> tag in the checkout.tpl file of OpenCart. Can anyone guide me on where to find thi ...

Encountered a 404 error while handling the Express 4 module, indicating that the 'html' module could not be

I need to update my express app to handle 404 (and 500) errors by displaying HTML instead of plain text. I have been able to show text to the client for 404 errors, but now I want to show HTML instead. My 404.html file is located in the /app directory. Cu ...

Customizing variables in React based on the environment

I am working on a React app that includes a chart component which calls an external API. When the app is running locally, the API URL is set to localhost:8080. However, when the app is deployed, the API URL needs to be changed to prod:8080. I have tried ...

Using Flickity API in Vue 3 with Typescript Integration

I have encountered an issue with implementing Flickity in my Vue 3 application. Everything works perfectly fine when using a static HTML carousel with fixed cells. However, I am facing difficulties when attempting to dynamically add cells during runtime us ...

Issue with rendering Backbone subview correctly

Today, I delved into the world of website development using backbone.js. Surprisingly, after a whole morning of trying to crack a puzzling problem, I find myself stuck. Let me focus on the crucial bits of code here. Initially, I have a View named Navigat ...