Cannot use my own TypeScript library in JavaScript

I’ve been banging my head against the wall with a seemingly simple task. I would appreciate any insights on this.

I’m writing a private library in TypeScript to be used in both TypeScript and JavaScript projects in our company.

The library works great but I cannot seem to be able to import it in JavaScript.

Library in TS

package.json

{
  "name": "rr-comm-bus-js",
  "version": "0.3.0",
  "description": "",
  "main": "lib/src/index.js",
  "types": "lib/src/index.d.ts",
  "scripts": {
    "dev": "ts-node-dev --respawn src/dev/dev.ts",
    "build": "rm -rf lib && tsc"
  },
  "keywords": [],
  "dependencies": {
    "redis": "^3.1.2"
  },
  "devDependencies": {
    "@types/node": "^16.4.12",
    "@types/redis": "^2.8.31",
    "nodemon": "^2.0.12",
    "ts-node-dev": "^1.1.8",
    "typescript": "^4.3.5"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "lib",
    "declaration": true,
    "noImplicitAny": true,
    "declarationMap": true,
    "allowJs": true
  },
  "lib": ["es2015"]
}

JavaScript (Node.js, where I want to consume this library)

Simplified code…

const MyModule = require("my-module-name");
const myModule = new MyModule(); <--- this line is where the error happens

So the error that I’m getting is:

const myModule = new MyModule();
          ^
TypeError: MyModule is not a constructor

Which would indicate that MyModule is not even a class, but it is. I DO get intellisense for the types in my TS library, but I cannot use the class.

Here is the transpiled TS to JS code:

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const declarations_1 = require("./declarations");
class Communicator {
    constructor() {
         // constructor logic
        };

        // more methods...

}
exports.default = MyModule;

I’ve tried following multiple articles and guides, changed tsconfig.json, and added “type”:”module” to package.json but for some reason, I simply cannot get this to work.

Any pointer would be very appreciated.

Answer

Try this

const MyModule = require("my-module-name").default;

const myModule = new MyModule();