Rollbar and typescript

1.1k views Asked by At

I'm stuck using rollbar with typescript, and their documentation is as poor as the AWS one.

I'm trying to build a reusable package, based on rollbar, and written with the latest TS version (4.2.4 as we speak)

So.. Let's dive into code parts (before anyone ask!).

In my index.ts, I import rollbar using

import Rollbar from 'rollbar';

as described in documentation

Some lines after, I just create the logger instance using a simple, dumb, new instruction:

const options = {
   // [...]
}
this._logger = new Rollbar(options);

In conjunction with the following tsconfig, I'm able to build and publish the final package.

{
    "extends": "@tsconfig/node14/tsconfig.json",
    "compilerOptions": {
        "rootDir": "src/",
        "outDir": "dist/",
        "declaration": true,
        "moduleResolution": "node",
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true
    },
    "include": ["src/index.ts"]
}


But, there is a but, for sure, otherwise they wouldn't be any question, when I'm trying to use the published package, I'm facing an error I'm not able to resolve.

TypeError: rollbar_1.default is not a constructor

That's not so strange. If I take a look at the generated JS, we can see that the import is done using importDefault, and the result is stored into rollbar_1.


const rollbar_1 = __importDefault(require("rollbar"));

class Logger {
  constructor(options, context) {
    const config = {
      accessToken: '',
      reportLevel: '',
      codeVersion: '',
      environment: ''
    };
    this._logger = new rollbar_1.default(config);
  }
}

Here I am, here I'm stuck.

I do not know what I'm looking for, and have no idea about the underlying error.

For those how want to help me, here is the tsconfig of the project using the package:

{
  "extends": "@tsconfig/node14/tsconfig.json",
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "outDir": "./dist/",
    "rootDir": "./src/"
  },
  "exclude": ["node_modules", "tests"],
  "include": ["src"]
}

For Sean, here is the result of "require('rollbar')"

enter image description here

It's definitely sure, the returned value is not helpful

I emailed Rollbar support to get some help.

1

There are 1 answers

1
Walt Jones On BEST ANSWER

If this is a CommonJS build (Node.js for example) the recommended syntax is:

import Rollbar = require('rollbar');

This may look strange, combining import with require, but it is what Typescript officially recommends: https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require

If it it es2015 or higher, import Rollbar from 'rollbar' should work. Make sure to set esModuleInterop in your tsconfig. https://www.typescriptlang.org/tsconfig#esModuleInterop