Muflix
Muflix

Reputation: 6798

TypeScript import : Failed to load resource (404)

I am coding my first typescript file and I have issue with package import.

The package I would like to use in my project is called showdown

libman.json

{
  "version": "1.0",
  "defaultProvider": "cdnjs",
  "libraries": [
    {
      "library": "[email protected]",
      "destination": "wwwroot/lib/showdown/"
    }
  ]
}

Snowdown files downloads through libman to wwwroot

enter image description here

My site.ts file looks like

import { showdown } from "../lib/showdown/showdown";

function ConvertMarkdownToHtml(markdown) {
    var converter = new showdown.Converter({ tables: true, strikethrough: true });
    var html = converter.makeHtml(markdown);
    return html;
}

I import the underlying site.js file to the webpage through script tag with module type.

enter image description here

@section Scripts {
    <script type="module" src="~/js/site.js"></script>
}

But I am getting following error

Failed to load resource: the server responded with a status of 404 (Not Found)

enter image description here

What am I missing ?

Update

the 404 error is related to site.js file.

it looks like, that site.js is not generated at all, because in site.ts is a mistake

enter image description here

../lib/showdown/ showdown has no exported member showdown

the following change do not throw any error

import * as showdown from "../lib/showdown/showdown";

export function ConvertMarkdownToHtml(markdown) {
    var converter = new showdown.Converter({ tables: true, strikethrough: true });
    var html = converter.makeHtml(markdown);
    return html;
}

but how I can call the ConvertMarkdownToHtml from the html file ?

Upvotes: 1

Views: 2904

Answers (2)

Muflix
Muflix

Reputation: 6798

I followed @Paul-Louis Mas answer with tip described here

index.html

@section Scripts {

    <script src="~/lib/showdown/showdown.min.js"></script>
    
    <script type="module">
         import { ConvertMarkdownToHtml } from "./dist/site.js"
    
         var html = ConvertMarkdownToHtml('...');
    </script>

site.js

declare var showdown: any;
export function ConvertMarkdownToHtml(markdown) {
    var converter = new showdown.Converter({ tables: true, strikethrough: true });
    var html = converter.makeHtml(markdown);
    return html;
}

and it works :-)

  • the declare var showdown: any; is the key how to use external js library without solving countless compile errors. Disadvantage is that we do not have intellisense available this way.

Upvotes: 1

Paul-Louis Mas
Paul-Louis Mas

Reputation: 429

After having Googled around a bit, it seems that you can't use imports from modules globally, so have you tried this:

@section Scripts {
    <script type="module">
        import { ConvertMarkdownToHtml } from '~/js/site.js';

        // Do the logic here using ConvertMarkdownToHtml
    </script>
}

Upvotes: 1

Related Questions