Typescript: how to import a class from a javascript file?

I would like to:

  • Imports a js file that defines the class: ./myClass/index.js
  • Declare public MyClass methods somewhere (in index.ts or the specified declaration file, I really don't know how to do this)
  • Have a typescript file that provides the class: index.ts

sort of

 // index.ts import MyClass from './myClass' // or require, or anything that would work export {MyClass} 

and

 // myClass/index.js export default class MyClass { ... } 

This obviously does not work, as importing ./myClass/index will not find the module.

The fact is that I tried to create the ./myClass/index.d.ts file based on this example , but in spite of everything, I still have the Error: the module error could not be found. /myClass/index.js at runtime: (

It seems to me that I have missed some basics of typescript, but I am trying to find some clear resources.

Any ideas?

+6
source share
2 answers

There is no export default class in JavaScript. What you can do is write your JS file. myClass/index.js

 "use strict"; class MyClass { hello(name) { console.log(`Hello ${name}`); } } exports.default = MyClass; 

Create type definitions for it. myClass/index.d.ts

 export default class MyClass { hello(name: string): void; } 

Then you can import it into your TypeScript like this.

 /// <reference path="./myClass/index.d.ts" /> import MyClass from "./myClass"; const my = new MyClass(); my.hello("Stack Overflow"); 
+6
source

at the end of your javascript file write this

 exports.MyClass = MyClass; 

in ts files

 import * as IzendaSynergy from './izenda/izenda_ui.js'; 

or

 import { IzendaSynergy } from './izenda/izenda_ui.js'; 

in tsconfig.json file

  "allowJs": true 
+1
source

Source: https://habr.com/ru/post/1012098/


All Articles