9

Imagine I have this simple TypeScript class, Animal.ts:

export default class Animal {
  constructor(public name : string) { }
}

With this tsconfig.json file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true
  },
  "files": [
    "Animal"
  ]
}

How can I use the compiled version of this class (compiled by running tsc) in a javascript file like so:

var Animal = require("./Animal");

var newAnimal = new Animal();

Should I edit something in my tsconfig.json file? The error I get is:

ReferenceError: Animal is not defined

Titulum
  • 9,928
  • 11
  • 41
  • 79
  • You can have typescript compile javascript files as well using 'allowJs' (in tsconfig.json). That way, you can reference typescript classes from your javascript. – Brian Dec 18 '17 at 21:42
  • 1
    Since you are using default export, I do believe you have to require it like `var Animal = require("./Animal").default` <-- note the `.default` at the end. – CRice Dec 18 '17 at 21:47
  • 1
    Exporting with `export default` makes your export an module. It would become `new Animal.default('name')`. However the error is not reproducible, the Animal is exported as `{ __esModule: true, default: [Function: Animal] }`. – Shane Dec 18 '17 at 21:47
  • @ShanevandenBogaard, and how should I edit the code to use `new Animal("name")` instead of `new Animal.default("name")`? – Titulum Dec 18 '17 at 21:51
  • 1
    You can do what `CRice` said or omit the `default` keyword – Shane Dec 18 '17 at 21:53
  • If I omit the `default` keyword, I still would have to use `var Animal = require("./Animal"); var newAnimal = new Animal.Animal("test");` instead of just `new Animal("test")`. How can I change it to do so? (without using `require("./Animal").default`) – Titulum Dec 18 '17 at 21:57
  • 1
    Yes, sorry I just noticed that. I have been using Babel which also exports it using `module.exports = ...`. You can do `const { Animal } = require('./animal');`. – Shane Dec 18 '17 at 22:07
  • That worked! Thank you very much! – Titulum Dec 18 '17 at 22:13

1 Answers1

9

As Shane van den Bogaard pointed out, the default keyword in Animal.ts needs to be omitted and :

const { Animal } = require('./Animal');

should be used instead of

var Animal = require('./Animal');

This way we can call the Animal class and initialize an object by using

const { Animal } = require('./Animal');
var newAnimal = new Animal("Clifford");
Sergey Yarotskiy
  • 4,536
  • 2
  • 19
  • 27
Titulum
  • 9,928
  • 11
  • 41
  • 79