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

8
  • You can have typescript compile javascript files as well using 'allowJs' (in tsconfig.json). That way, you can reference typescript classes from your javascript. Commented Dec 18, 2017 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. Commented Dec 18, 2017 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] }. Commented Dec 18, 2017 at 21:47
  • 1
    You can do what CRice said or omit the default keyword Commented Dec 18, 2017 at 21:53
  • 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');. Commented Dec 18, 2017 at 22:07

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

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.