cloudamqp / amqp-client.js

AMQP 0-9-1 TypeScript client both for Node.js and browsers (using WebSocket)
https://cloudamqp.github.io/amqp-client.js/
Apache License 2.0
200 stars 19 forks source link

[TS + Node + ESM] AMQPBaseClient can't be found #82

Closed PeS82 closed 1 year ago

PeS82 commented 1 year ago

When using the library in TypeScript project configured to use ESM the imports from types are failing.

package.json has "type": "module"

tsconfig:

  "compilerOptions": {
    "module": "ES2022",
    "moduleResolution": "nodenext",
    "target": "ES2022",
  }

The AMQPBaseClient is then imported as

import { AMQPBaseClient } from '@cloudamqp/amqp-client/types/amqp-base-client.js';`

and during runtime (using ts-node-esm) or compilation (tsc) it fails with error

Cannot find module '@cloudamqp/amqp-client/types/amqp-base-client.js' or its corresponding type declarations.

The solution I came up with is to add export to node_modules/@cloudamqp/amqp-client/types/index.d.ts:

export { AMQPBaseClient } from '../types/amqp-base-client.js';

and then import in the project simply as

import { AMQPBaseClient } from '@cloudamqp/amqp-client';

Not sure whether this is the right solution. Could you please modify the library to work with ESM?

carlhoerberg commented 1 year ago

Why are you importing the base client? Import the socket client.

PeS82 commented 1 year ago

Because amqp.connect() (AMQPClient) returns AMQPBaseClient.

There is exported AMQPWebSocketClient which is not what I want (I believe) in the server environment (i.e. not in the browser)?

ngbrown commented 1 year ago

In your tsconfig.json set moduleResolution to either bundler or node16. Then import like this:

import { AMQPBaseClient } from "@cloudamqp/amqp-client/amqp-base-client";

If you are only using it as a type, then adding the type specifier will remove it from the built output:

import type { AMQPBaseClient } from "@cloudamqp/amqp-client/amqp-base-client";
PeS82 commented 1 year ago

Thank you very much for the help, quick response and for the library. It is resolved now.