Reputation: 569
I'm just using the code as a learning exercise regarding JavaScript classes.
The code produces a "TypeError: SimpleLogger is not a constructor". The class seems to be exported Ok but I can't instantiate it in the main.js file.
I've reduced the code to just show the issue. I was wondering if anyone can spot the problem. Thanks.
// In simplelogger.js
"use strict";
class SimpleLogger {
constructor(level) {
this.level = level || DEFAULT_LEVEL;
}
// .... other methods
}
const DEFAULT_LEVEL = 'info';
module.exports = {
SimpleLogger,
DEFAULT_LEVEL
}
// In main.js
"use strict";
const SimpleLogger = require('./simplelogger.js');
let log = new SimpleLogger('info');
The error is produced in the last line.
Upvotes: 5
Views: 22482
Reputation: 24638
Here is another way to use your class:
const { SimpleLogger } = require('./simplelogger.js');
let log = new SimpleLogger('info');
Or if you need both keys:
const { SimpleLogger, DEFAULT_LEVEL } = require('./simplelogger.js');
let log = new SimpleLogger('info');
Upvotes: 0
Reputation: 5204
You're exporting an object containing both SimpleLogger
and DEFAULT_LEVEL
therefore to use it in main.js you need to reference it properly like so
const SimpleLogger = require('./simplelogger.js').SimpleLogger;
let log = new SimpleLogger('info');
If you only want to export SimpleLogger
you can change your export like so
module.exports = SimpleLogger
Then you can require SimpleLogger
as you do in your code.
Upvotes: 7