Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import ES6 module from http url in Typescript

I am writing an ES6 module which depends on the other ES6 module specified with http url like this:

import { el, mount } from "https://cdnjs.cloudflare.com/ajax/libs/redom/3.26.0/redom.es.js";
const pElem = el("p") // definitely works in Javascript

When I tried to translate my module in Typescript, I got this error:

Cannot find module 'https://cdnjs.cloudflare.com/ajax/libs/redom/3.26.0/redom.es.js' or its corresponding type declarations.

I'm using ts-watch npm module to compile Typescript, and it works fine unless I don't use the import from https://....

I also know that if I tried to import npm module (e.g. import {el} from "redom") it works as well. But what I am writing is a module for web browser, not that of npm. With this reason, using webpack is not an option.

like image 594
pocorall Avatar asked Mar 03 '23 09:03

pocorall


2 Answers

Thanks to @acrazing's comment, I managed to resolve this problem. Here's how:

In a new ts file:

declare module 'https://*'

This mutes the error that Typescript compiler attempts to read type declaration.

If you want to access type declaration as a node dependency, paste this in a new ts file:

declare module 'https://cdnjs.cloudflare.com/ajax/libs/redom/3.26.0/redom.es.js' {
    export * from 'redom'
}

and add redom dependency in package.json

  "dependencies": {
    "redom": "3.26.0",
    ...
  },

Then, type declaration is read from local ./node_modules directory, VSCode recognizes the types as well.

like image 74
pocorall Avatar answered Mar 04 '23 23:03

pocorall


declare module 'https://*' somehow doesn't work for me so I simply ignore it.

// @ts-ignore Import module
import { Foo } from "https://example.com/foo.ts";

// Now you can use Foo (considered any)
like image 42
Luke Vo Avatar answered Mar 04 '23 22:03

Luke Vo