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
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With