13

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.

4
  • Does this answer your question? Import TypeScript Module from a Uri Commented Jun 1, 2020 at 1:58
  • It's close to my case. But I want to use ES6 import in my code, which currently results compilation error from Typescript. Is there a way to mute this error? Commented Jun 1, 2020 at 2:33
  • If you just want to mute typescript error, you can try this: typescriptlang.org/play?#code/… Commented Jun 1, 2020 at 2:48
  • That's what I wanted to do! Thank you! Commented Jun 2, 2020 at 0:05

2 Answers 2

20

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This didn't do anything for me until I placed it in the src folder with the rest of my files, rather than in a separate top level types folder. Honestly not sure why that mattered yet, probably some esoteric tsc resolution thing. So, <PROJECT>/src/types/redom.d.ts rather than <PROJECT>/types/redom.d.ts for me.
Whups, looks like my issue was actually forgetting to set the TS compiler option "moduleResolution": "node".
4

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.