Exploring the possibilities with Rollbar and TypeScript

Struggling with Rollbar and TypeScript, their documentation is about as clear as AWS's.

I'm in the process of creating a reusable package based on Rollbar, utilizing the latest TS version (currently 4.2.4).

Let's delve into some code snippets without further delay!

In my index.ts file, I bring in Rollbar like so:

import Rollbar from 'rollbar';

This method is documented by Rollbar themselves.

Few lines down, I simply instantiate the logger using a straightforward new statement:

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

Coupled with the below tsconfig setup, I manage to successfully build and release the package:

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


However, there's a hiccup - an error surfaces when trying to utilize the published package that has me perplexed.

TypeError: rollbar_1.default is not a constructor

Upon inspecting the generated JS, it appears the import uses importDefault and assigns the result to 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, stuck without a clue.

The root cause eludes me, and I can't pinpoint the issue at hand.

For those willing to lend a hand, here's the project's tsconfig using the package:

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

And for Sean, here's the outcome of "require('rollbar')":

https://i.stack.imgur.com/T4gnW.png

The output isn't offering much assistance.

I've reached out to Rollbar support for guidance.

Answer №1

When working with a CommonJS build (such as Node.js), it is recommended to use the following syntax:

import Rollbar = require('rollbar');

Although it may seem unusual to combine import with require, this is actually the official recommendation from Typescript: https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require

If you are using es2015 or higher, import Rollbar from 'rollbar' should also work. Just remember to configure esModuleInterop in your tsconfig file. https://www.typescriptlang.org/tsconfig#esModuleInterop

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The switchMap function in Angular does not trigger the async validator as expected

To ensure that the username entered by the user is unique, I am sending an HTTP request for every input event from the target element. It is important to debounce this operation so that only one HTTP request is made for X consecutive input events within a ...

Generate the URL based on the JSON feed

Can someone help me figure out what I'm doing wrong here? I'm attempting to create the image URL using the flickr.photos.search method now (I need to show images close to the visitor's geolocation), it was working with groups_pool.gne befor ...

Send visitors to a different page for a brief 10-second interlude before bringing them back to where they started

Is there a way to create a temporary redirect for users to an ad page and then automatically return them to their desired page after 10 seconds? I have limited knowledge of PHP and Java, so I would appreciate any guidance or complete redirect code that co ...

Retrieving multiple selected row values using an ASP Repeater

Within my repeater, I have three values bound: a visible "User Name" column, a visible "Business" column, and a hidden field called "UserId". My goal is to implement the following functionality: when a row is clicked, it should highlight in a different c ...

After loading the ajax content, remember to include the JavaScript files

Here's the situation: I am importing some php files, one of which includes a slider that requires .js files. However, when I make an ajax call, the file is imported but the js files are not. Is this normal behavior? I attempted the following: var s ...

Name the Angular interpolation function with the (click) event

I have a JSON file that defines different dynamic buttons, but when I click on them, the function is not being called. Here's how my JSON file looks: export const liveButtonData = [ { title: 'My Name', function: 'getName()'} ...

Indicate a specific type for the Express response

Is there a method to define a specific type for the request object in Express? I was hoping to customize the request object with my own type. One approach I considered was extending the router type to achieve this. Alternatively, is there a way to refactor ...

Managing form submissions using Material UI and Next.js

Can someone provide insights on using Material UI with Next Js? I am experimenting with a Login template from Material UI, but I am facing an issue where query params are added to the URL upon Submit. For example: localhost:3000/auth/login changes to: ...

In Laravel, Inertia.js will automatically close a modal if there are no validation errors present

Here is the method I am currently using: methods: { submit() { this.$inertia.post('/projects', this.form); this.openModal = false; }, }, Unfortunately, this method closes the modal even if there are validation erro ...

React Error: Invalid Element Type with Named Exports

I've been diving into the world of React hooks and functions, working on three different files. First, there's one that establishes a context called SummaryContext. The second file contains a class component that consumes this context named WikiS ...

Transfer the parameter from ajax function to the aspx.cs file

I've written some code using HTML, JS, and AJAX, but it's not functioning as expected. <script type="text/javascript"> function DeleteSelectedRecord(id) { alert(id); $.ajax({ type: "POST", ...

Angular click switch Component keeps track of its previous state

I recently developed an Angular component that consists of a button and an icon. One key requirement is for each instance of this component to retain its own status. For example, let's say we have three instances in the app.component.html: <app-v ...

Material UI - The array is unexpectedly resetting to contain 0 elements following an onChange event triggered by the TextField component

As I work on developing an application, one of the key features involves allowing users to select others from a list with whom they can create a group chatroom. Additionally, there is a TextField where they can assign a name to their newly created group. ...

In Backbone.js, specialized events are dispatched to cater to unique needs

In search of a sleek JavaScript animation to have some balls gracefully moving within a canvas, I aim to implement collision detection using custom events managed through Backbone.js rather than resorting to an intricate nested loop to monitor interactions ...

Instructions for automatically sending SMS when there is a change in MySQL database data using PHP

Is it possible to trigger an SMS using Twillo as the gateway when there is a change in data in a MySQL database with PHP? ...

jquery events fail to trigger following the dynamic loading of new content

I have developed a voting system that utilizes images. When a user clicks on an image, it submits the vote and fades out before reloading using a PHP page. The issue I'm facing is that after the first submit, clicking on the images does not trigger an ...

Trouble arises in TypeScript when defining a class - SyntaxError crops up

When I try to declare a class, I encounter an error: // The code below is from my test1.ts file class WDesign { wModel: string; wQuer: string; } let logWDesign = (wd : WDesign) => { console.log(wd.wModel + " " + wd.wQuer); } let wd1 : WDe ...

The knockout click event isn't functioning properly for a table generated by ko.computed

My goal is to connect a table to a drop-down menu. Here are the key points of what I'm trying to achieve: The drop-down should list MENUs. Each MENU can have multiple MODULES associated with it, which will be displayed in the table based on the ...

Utilizing the `in` operator for type narrowing is yielding unexpected results

Attempting to narrow down a type in TypeScript: const result = await fetch('example.com') if (typeof result === "object" && "errors" in result) { console.error(result.errors); } To clarify, the type of result before the if condition should be ...

Not adhering to directive scope when transclusion is used, despite explicit instructions to do so

Trying to use a transcluding directive within another controller, but the inner scope isn't being redefined as expected. Despite trying different methods, I can't seem to figure out what's going wrong. The simplified code looks like this: ...