#Using CommonJS module in ESM

2 messages · Page 1 of 1 (latest)

cobalt galleon
#

I'm trying to use https://www.npmjs.com/package/xvfb (commonJS) in an ESM script I'm writing

I tried doing something like

async function main() {
  const Xvfb = (await import('xvfb')).default;
  const xvfb = new Xvfb({ reuse: true, timeout: 30000, silent: true });
  xvfb.startSync();
}```

I however ran into a few errors 

```js
index.ts:52:30 - error TS7016: Could not find a declaration file for module 'xvfb'. 'project/node_modules/xvfb/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/xvfb` if it exists or add a new declaration (.d.ts) file containing `declare module 'xvfb';`

52   const Xvfb = (await import('xvfb')).default;
                                ~~~~~~

node_modules/long/umd/index.d.ts:1:18 - error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("../index.js")' call instead.

1 import Long from "../index.js";
                   ~~~~~~~~~~~~~


Found 2 errors in 2 files.

Errors  Files
     1  index.ts:52
     1  node_modules/long/umd/index.d.ts:1```

I managed to find a types file that someone wrote in the past and with a bit of modification I got
#
import {ChildProcess} from 'child_process';

declare class Xvfb {
  protected readonly _display: `:${number}`;
  protected readonly _reuse?: boolean;
  protected readonly _timeout: number;
  protected readonly _silent?: boolean;
  protected readonly _xvfb_args: string[];
  protected readonly _process: ChildProcess;

  constructor(options?: Xvfb.Options);

  start(cb: Xvfb.Callback);

  startSync(): ChildProcess;

  stop(cb: Xvfb.Callback);

  stopSync();

  display(): `:${number}`;
}

declare namespace Xvfb {
  interface Options {
    displayNum?: number;
    reuse?: boolean;
    /**
     * Maximum time to start/stop xvfb process.
     * @defaultValue 500
     */
    timeout?: number;
    /**
     * Whether or not to write errors to the stderr of the current process.
     * @defaultValue false
     */
    silent?: boolean;
    xvfb_args?: string[];
  }

  type Callback = ((error: Error) => void) | ((error: null, process: ChildProcess) => void);
}

export = Xvfb;```