Greg Gum
Greg Gum

Reputation: 37919

How to require a class file in node.js

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

Answers (3)

Fabian Lauer
Fabian Lauer

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

Greg Gum
Greg Gum

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

Teddy Sterne
Teddy Sterne

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

Related Questions