google / zx

A tool for writing better scripts
https://google.github.io/zx/
Apache License 2.0
42.8k stars 1.09k forks source link

Importing this package into CJS project triggers false-positive TypeScript error #871

Open grabbou opened 1 month ago

grabbou commented 1 month ago

Expected Behavior

The following should work without any errors:

import { $ } from 'zx'

Actual Behavior

Triggers the following error:

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("zx")' call instead.
  To convert this file to an ECMAScript module, change its file extension to '.mts', or add the field `"type": "module"` to 'package.json'.ts(1479)

However, the project works just fine. This is because main in package.json is set to a CJS entry-point (thank you!)

The only alternative I am aware of is setting {type: module} inside esm build directory. It would be great if zx could be used in both ESM and CJS projects without warnings.

antongolub commented 1 month ago

@grabbou,

Could you provide a full code example for debug?

grabbou commented 1 month ago

Hey!

So the issue is happening in our repository https://github.com/rise-tools/rise-tools

index.ts - https://github.com/rise-tools/rise-tools/blob/main/packages/cli/src/zx.ts package.json - https://github.com/rise-tools/rise-tools/blob/main/packages/cli/package.json#L37 tsconfig.json - https://github.com/rise-tools/rise-tools/blob/main/packages/cli/tsconfig.json (we're using @tsconfig/node18 and outputting CJS)

Platform: Mac OS, Node 20 ZX version: ^8.1.4

This could be related https://github.com/microsoft/TypeScript/issues/49299

grabbou commented 1 month ago

I would be happy to look into this and provide a proposed solution, once approved, submit a follow up PR. @antongolub et al, please let me know if you would consider a PR that fixes this.