functions icon indicating copy to clipboard operation
functions copied to clipboard

Invalid type definitions - static import of ESM types from CJS types

Open benmccann opened this issue 2 years ago • 6 comments

Describe the bug

../../node_modules/.pnpm/@[email protected]/node_modules/@netlify/functions/dist/function/v2.d.ts:1:30 - 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("@netlify/serverless-functions-api")' call instead.

1 export type { Context } from '@netlify/serverless-functions-api';
                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Found 1 error in ../../node_modules/.pnpm/@[email protected]/node_modules/@netlify/functions/dist/function/v2.d.ts:1

Configuration

Import the library in a project which has the following in the tsconfig.json:

		"module": "node16",
		"moduleResolution": "node16",

This issue can be worked around with "skipLibCheck": true, so ensure that is not set when reproducing. It is not set by default.

benmccann avatar Dec 01 '23 19:12 benmccann

Thanks for reporting this! It's good to know there's a workaround, i'll add it to our internal triage.

Skn0tt avatar Dec 05 '23 07:12 Skn0tt

I'm a bit surprised about TypeScript emitting this error for a .d.ts file. That can't use require anyways, right?

Skn0tt avatar Dec 05 '23 09:12 Skn0tt

They're not using require, but you can only import CJS from ESM if you use a dynamic import. Another possible solution besides updating the types would be to distribute this package as ESM.

benmccann avatar Dec 05 '23 12:12 benmccann

They're not using require, but you can only import CJS from ESM if you use a dynamic import.

We're only importing @netlify/serverless-functions-api for types:

https://github.com/netlify/functions/blob/main/src/function/v2.ts#L1

So I don't think that an actual import line shows up in the generated JS file. This seems to be purely about the declaration file that TypeScript generates, and I would have expected TypeScript to generate it in a way that's compliant with CJS, because that's how it's configured:

https://github.com/netlify/functions/blob/755237528a51e88204b22f07cd47e93a7ea42759/tsconfig.json#L27

Anyways, distributing this as ESM makes sense to me. @eduardoboucas do you see any reason why this might become a problem? Maybe consumption from within Next.js sites?

Skn0tt avatar Dec 05 '23 12:12 Skn0tt

I think this will be fixed by #473

ascorbic avatar Feb 13 '24 13:02 ascorbic