Home > Net >  Linking javascript as content doesn't work in visual studio
Linking javascript as content doesn't work in visual studio

Time:12-09

I have two projects (MAUI and ASP.NET). In both I use Blazor and therefore I can write a shared code for native as well as for web applications. So far everything works perfectly and I have no duplicate code.

Now I have the first JavaScript function that I am implementing and there are problems now. I implement the JS function in the native project (MAUI) at wwwroot/js/Scripts.js. I can then call the function from the native app (Windows or Android) it works!

Now, for the Webproject, I also created the js directory under wwwroot and linked the javascript file from the native MAUI Project. As build action I set content and set it to "always copy". This doesn't seem to work, the javascript function is not called in the Webproject, but no error is triggered.

But if I don't link the javascript file but import (or create new Script.js) it works in the webproject and the JS function is called!

I have tried all possible build actions, none of them seems to be able to detect a linked JS file!

Does anyone know how to make it so that I only have the JS file in one project and then just link (not copy) it to the second project?

Thanks

CodePudding user response:

Don't use an application project for shared content or components - they should be in a RazorClassLibrary, referenced in both application projects.

Linked content files are not supported in aspnetcore.

CodePudding user response:

...I finally used RCL, but only for JS and it works. Now it is important to include script correctly, otherwise you will search for a long time:

<script src="_content/CALCrcl/js/Scripts.js"></script>

I was thinking briefly about outsourcing all Razor components to RCL (i.e. not using the components via linking from MAUI to ASPNET), but at first it seems like that would be more effort than what I'm currently doing.

The following page describes how to use RCL between MAUI native and web:

https://learn.microsoft.com/en-us/aspnet/core/blazor/hybrid/class-libraries?view=aspnetcore-7.0

https://learn.microsoft.com/en-us/aspnet/core/blazor/components/class-libraries?view=aspnetcore-7.0&tabs=visual-studio

After a few tries I decided to stay with the old one, not least because of codebehind and namespace, as it is not clear from the MS doc how to solve the problem via RCL.

  • Related