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

Using toLocaleDateString method in Node for handling dates

After using toLocaleDateString in the browser, I noticed that it returns: n = new Date() n.toLocaleDateString() "2/10/2013" However, when using node.js, the format is completely different: n = new Date() > n.toLocaleDateString() 'Sunday, Februar ...

What occurs when the update function returned by React.useState() is invoked?

Just recently, I delved into the world of React hooks and decided to implement a small feature using them. The feature enables hidden texts to be displayed when users click on hyperlinks. Although I managed to make the code work, it appears that there are ...

Having trouble obtaining the serialized Array from a Kendo UI Form

I am working on a basic form that consists of one input field and a button. Whenever the button is clicked, I attempt to retrieve the form data using the following code: var fData = $("#test").serializeArray(); Unfortunately, I am facing an issue where I ...

AngularJS: Monitoring $locationChangeStart for token verification

I am attempting to check if the next has a token or not, but it is not working and I am getting an error: TypeError: Cannot read property 'next' of undefined Any suggestions? app.js .run(function ($rootScope, $location,$log,User) { ...

Leveraging external JavaScript libraries in SAPUI5

I'm currently facing an issue while trying to include an external .js file in my SAPUI5 Controller. jQuery.sap.includeScript("externalLibrary.min.js", function() { // initializing objects from the library }); Despite setting up ...

How to retrieve the outcome of a stored procedure using node.js

Is it possible to retrieve multiple select results from distinct tables (many rows) in just one stored procedure in mysql and then access those results in nodejs? In .NET with SQL Server, we can use "sqlnextresult" for this purpose. VIEW IMAGE FROM STORE ...

Using Angular DI to inject a specific token value into a provider factory

Can an InjectionToken be injected into a factory provider? This is what I have implemented: export const HOST_TOKEN = new InjectionToken<string>("host"); let configDataServiceFactory = (userService: UserService, host: string) => { return ne ...

Angular's table data display feature is unfortunately lacking

Below is a simple HTML code snippet: <div class="dialogs"> <div id="wrapper" > <p>{{createTestingConstant()}}</p> <ng-container *ngFor="let one of contacts"> <p>{{one ...

Traverse through the loop with React Material UI in JavaScript

Hi everyone, I'm having trouble with this code. I want to iterate through an object called paleogenome.data and create a CardHeader for each item: { Object.keys(paleogenome.data).forEach(function (key){ console.log(paleogenome.data[key] ...

Tips on implementing v-show within a loop

Hey @zero298, there are some key differences in the scenario I'm dealing with. My goal is to display all the items in the object array and dynamically add UI elements based on user input. Additionally, v-if and v-show function differently (as mentione ...

The type 'NextApiRequest' lacks the following attributes compared to type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'

An error has been identified in the code for a Next.js project below. The error message reads: Argument of type 'NextApiRequest' is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any ...

Unable to properly execute Fetch Delete Request

When using the Fetch API, I am sending this request: const target = e.currentTarget; fetch(target.href, { method: 'delete', }) .then(res => console.log(22)) .catch(err => console.log(err)); In addition, here is the middleware that manag ...

Issues with Implementing Scroll Directive in Angular JS

Apologies for asking what may seem like a silly question. I'm still new to using AngularJS and recently came across a neat little scroll directive on http://jsfiddle.net/88TzF/622/. However, when I tried implementing the code in the HTML snippet below ...

Understanding Joi validation - setting a field as optional depending on the input received

I have been struggling to integrate the following joi validation. joiSchema = Joi.object().keys({ taskno: Joi.string().alphanum().required().uppercase().trim(), taskstatus: Joi.valid('G', 'C', 'I', 'S'), ...

Issue encountered when attempting to redirect following a jQuery Ajax request

I attempted to create a redirection mechanism upon receiving a successful response from the server. I followed instructions here, but unfortunately, I couldn't get it to work as intended. Below is the function responsible for sending data to the serv ...

AngularJS does not update values properly if there is a style applied to the parent container

I'm struggling to find the best approach to handle this situation. This is how my AngularJS code looks: <span class="something" ng-hide="onsomecondition"> {{value}} </span> .something{ text-align:left; padding:10px;} Issue: The value ...

`When you extend a $resource object, it effectively removes the prototype from the

Here's the current code snippet I'm working with: // Factory angular.factory('Student', function() { var defaults = { StudentId: null }; var Student = function(params) { angular.extend(this, angular.copy(de ...

Search for all documents in MongoDB and update all of them except for one

After performing a database lookup, I am receiving an array of objects as a result. [ { name: "test", services: { credentials: "123456" } }, { name: "test1", services: { credentials: "1 ...

Substituting placeholders within a docx template remains incomplete

Utilizing this specific library, I am implementing a feature to substitute placeholders within a docx template and generate multiple documents. The technologies involved are neutralino and vue for the front-end, where I have devised a method that transmits ...