Home > other >  Include Javascript library with @ sign in .NET core MVC application
Include Javascript library with @ sign in .NET core MVC application

Time:12-30

Currently I'm working on a .NET core MVC app wired up with yarn to add packages. So far I've added the Signalr package like this: yarn add @microsoft/signalr

Which adds the package to /wwwroot/lib/@microsoft/signalr/etc..

However when I try to include the package in the Web app it gets stuck. I'm including it like this: <script src="lib/@microsoft/signalr/dist/browser/signalr.js"></script>

also <script src="lib/microsoft/signalr/dist/browser/signalr.js"></script> does not work.

Anyone knows how to fix this? We do not want to switch to libman and prefer to keep using packages with Yarn.

Cheers!

CodePudding user response:

Firstly, you need know that Yarn will not install the client side package to your wwwroot by default.

It globally downloads the package in %UserProfile%\AppData\Local\Yarn\ folder.

In my PC, it exists in C:\Users\username\AppData\Local\Yarn\Cache\v6:

enter image description here

The whole working steps

  1. Be sure you have installed note.js, then run following command to install Yarn :

     npm install --global yarn
    
  2. Run command to add signalr package:

     yarn add @microsoft/signalr
    
  3. Find the signalr package(@microsoft folder) in %LOCALAPPDATA%\Yarn\ and copy the whole @microsoft folder:

    enter image description here

  4. Paste the whole @microsoft folder to your project wwwroot/lib folder:

    enter image description here

  5. Then add the js reference like below:

    <script src="@Url.Content("/lib/@microsoft/signalr/dist/browser/signalr.js")"></script>
    

    enter image description here


Actually I suggest you can use Libman, it can directly download to your wwwroot folder.

CodePudding user response:

You cannot use the package like that in your Webclient.

Everything you want accessible from your Client must be served by your Server.

Serving a Package is a bit more tricky and I would recommend using a bundler.

With Webpack for example you can prepare your client Resources to be served.

In practice this can look like this:

Webpack is configured to bundle your Client Javascript and put it in <project-root>/assets

Your server is configured to serve every file from the <project-root>/assets directory to the /assets route.

In your client script file you import your library module like so:

import {<your needed parts>} from '@microsoft/signalr';

Finally your html page loads your client script like so:

<script src="/assets/bundle.js" type="module"></script>

This is a simplified example and i would recommend you to read the Webpack docs.

  • Related