Reputation: 37919
I am learning node.js in Visual Studio 2017.
I have this class in it's own file called "logger.ts":
export default class Logger {
log(data)
{
console.log(data);
}
}
I then try to use that in my node project:
declare var require;
var Logger = require('./logger.js');
var anInstance = new Logger();
anInstance.log('test');
I get the error "Logger is not a function".
How am I supposed to do this?
Upvotes: 1
Views: 1123
Reputation: 9897
TypeScript offers import statements, which are based on the ES 2015 language specification.
In your case, you could use it like this:
// logger.ts
export class Logger { ... }
// main.ts
import { Logger } from "./logger";
var a = new Logger();
a.log('test');
When you use default export
, you don't need the braces in the import statement:
// logger.ts
export default class Logger { ... }
// main.ts
import Logger from "./logger";
You can also combine default
and non-default exports, like this:
// logger.ts
export class Logger { ... }
export default Logger;
// example1.ts
import Logger from "./logger"; // works
// example2.ts
import { Logger } from "./logger"; // works too
Upvotes: 1
Reputation: 37919
Since this is typescript, I should have been using the typescript style of import as suggested by @FabianLauer.
export class Logger {
log(data)
{
console.log(data);
}
}
And then importing it:
import { Logger } from "./logger";
var anInstance = new Logger();
anInstance.log('test');
I was thinking that the import would be different because this was node.js, but it's exactly the same as a client app.
Upvotes: 1
Reputation: 14221
I think the issue you are seeing is with how the Logger is being imported. The declare var is unneccesary and you should not need to specify the file extension. Try the following in your server side code.
var Logger = require('./logger');
var anInstance = new Logger();
anInstance.log('test');
Upvotes: 1