I am using a third party CommonJS (CJS) library without types. My project is CJS with TypeScript. The importation works just fine (imports are transpiled to requires) if I disable errors using comments.
/* c8 ignore start */
// @ts-ignore
import * as func from "third-party-library";
const example = func();
I wanted to get rid of these comments and get some more accurate typing, so I created a .d.ts
file for the library. It appears to be accurate thanks to this answer and my IDE / eslint no longer complains about unknown types or the use of any
;
// third-party-library.d.ts
declare module "third-party-library" {
function func(): string;
export = func;
}
All good so far, except now I get the following error;
This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export.ts(2497)
I have read that the 'fix' for this is to add the esModuleInterop
flag in my tsconfig.json
as described.
However, I don't think this is the real fix because I am importing a CJS module into my pure CJS project. No modules or libraries are ESModules (ESM) I shouldn't need to do this.
As such, I believe that perhaps the declare
in the library .d.ts
is not quite accurate and the notation I am using is for ESM modules? Or perhaps I am importing incorrectly.
How can I resolve this without using esModuleInterop
.
The answer was in this (ambiguously named) question.
// third-party-library.d.ts
declare module "third-party-library" {
function func(): string;
namespace func { }
export = func;
}