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

25,078

Solution 1

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

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

}
exports.default = MyClass;

Create a Type definitions for it. myClass/index.d.ts

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

You can then 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");

Solution 2

at the end of the 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
Share:
25,078
aherve
Author by

aherve

PhD, expert CTO, cloud architect &amp; data engineer

Updated on March 22, 2020

Comments

  • aherve
    aherve about 4 years

    I would like to :

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

    something like

    // 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 the import of ./myClass/index won't find the module.

    The thing is, I tried to create a ./myClass/index.d.ts file based on this example, but no matter what, I still have a Error: Cannot find module './myClass/index.js' error at runtime :(

    I feel like I miss some typescript basics here but I'm striving to find some clear resources.

    Any ideas ?

  • aherve
    aherve over 7 years
    Can't believe it was that simple 0_o. Thanks a lot !
  • titusfx
    titusfx almost 4 years
    @goenning why do you say there is not export default class ? developer.mozilla.org/en-US/docs/web/javascript/reference/… . I think that statement may confuse people
  • rmirabelle
    rmirabelle over 3 years
    allowJs was key for me. Thanks!
  • darkomen
    darkomen about 3 years
    Me I don't use exports.MyClass = MyClass but export default class MyClass with the "allowJs": true