javascripttypescriptvitesuperagent

Uncaught TypeError: Class extends value #<Object> is not a constructor or null - with superagent-throttle


I am trying to import the npm package superagent-throttle in my TypeScript project, but when I do so I get this message:

Uncaught TypeError: Class extends value #<Object> is not a constructor or null

If I use require it works fine:

const Throttle = require("superagent-throttle");

But, I've started using Vite which does not allow require so I have to use import instead.

The code where I reference it wants to instantiate a class ie:

        this.throttle = new Throttle({
            // set false to pause queue
            active: true,
            // how many requests can be sent every `ratePer`
            rate: 10000,
            // number of ms in which `rate` requests may be sent
            ratePer: 1000,
            // How many requests can be sent concurrently
            concurrent: 2
        });

I have tried different variations of the import statement, but none of these work for me:

import { Throttle } from "superagent-throttle";
import Throttle from "superagent-throttle";
import * as Throttle from "superagent-throttle";

They all give the same result - they compile ok but fail at runtime with the same error message (as above).

The code in the superagent-throttle JS file looks rather obscure, I have no idea what it's trying to do, so I'm struggling to try and understand how I could fix this issue:

Package file: node_modules/superagent-throttle/dist/index.js:

'use strict';

var _events = require('events');

var _events2 = _interopRequireDefault(_events);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
...
class Throttle extends _events2.default {
  constructor(options) {
    super();
    // instance properties
    this._options({
      _requestTimes: [0],
      _current: 0,
      _buffer: [],
      _serials: {},
      _timeout: false
    });
... etc ...

Solution

  • The error message points to _events2.default in the offending code:

    var _events = require('events');
    
    var _events2 = _interopRequireDefault(_events);
    ā‹®                                šŸ‘‡ /* not a constructor or null */
    class Throttle extends _events2.default {
    

    The debugger reveals that _events.default is stubbed as an empty object, which means the events module is not available. events (from Node) is normally unavailable in the browser, leading to the error you observed.

    One solution is to install an events shim:

    npm i -S events
    

    demo