Lukas
Lukas

Reputation: 10340

Typescript default export undefined

I am writing an npm module, a simple logger. I wrote this in plain JS:

logger.js

class Logger {
  // stuff
}

module.exports = Logger;

In a js script, this works fine:

logger-test.js

const Logger = require('ep-logger');

const logger = new Logger('my-logger');
logger.info('yo');

But we at our company use TypeScript. So next to my logger.js I created a file logger.d.ts which reads as follows

export interface SplunkOptions {
    endpoint?: string
    loggingSource?: string
    loggingSourceType?: string
}

export interface LoggerOptions {
    stage?: string
    level?: string
    splunk?: SplunkOptions
}

export default class Logger {
    constructor(name: string);

    public static setOptions(obj: LoggerOptions): void;

    public error(message: string | Error, ...data: any[]): void;
    public warn(message: string | Error, ...data: any[]): void;
    public info(message: string | Error, ...data: any[]): void;
    public verbose(message: string | Error, ...data: any[]): void;
    public debug(message: string | Error, ...data: any[]): void;
    public silly(message: string | Error, ...data: any[]): void;
}

In my package.json I did this:

{
  // more package.json stuff here
  "main": "src/logger.js",
  "types": "src/logger.d.ts"
}

Now in my TypeScript-Project I am trying to use my logger:

index.ts

import Logger from 'ep-logger';

const logger: Logger = new Logger('my-logger');
logger.info('yo');

But I get an error that my logger does not have a default export:

{ Error: Command failed: ts-node local-lambda.ts --colors

/Users/luke/Arbeit/WeltN24/Editorial Products/projects/ep-logger-tests/js-app/yo-lambda/src/index.ts:5 const logger: Logger = new Logger('my-logger'); ^ TypeError: ep_logger_1.default is not a constructor ...

In fact, if I do

console.log(Logger);

I get

undefined

Upvotes: 3

Views: 3459

Answers (1)

artem
artem

Reputation: 51579

With current version of typescript (2.6 or below), you need to write your definition file with export assignment instead of default export:

export interface SplunkOptions {
    //...
}

export interface LoggerOptions {
    //...
}

export class Logger {
    //...
}

export = Logger;

It seems like the plan is to change all that in the next version (2.7), and the way you have it written originally will start working (breaking export = in the process), initially behind the --strictESM flag, then, starting from 2.8, as default behavior without any flags.

Upvotes: 2

Related Questions