Skip to content

@wordpress/api-fetch works weirdly with ES modules #59087

@anomiex

Description

@anomiex

When using @wordpress/api-fetch in a TypeScript library, tsc complains that apiFetch is not callable.

The problem being encountered here is described in depth at https://github.com/arethetypeswrong/arethetypeswrong.github.io/blob/main/docs/problems/CJSOnlyExportsDefault.md

Example

package.json
{
	"type": "module",
	"dependencies": {
		"@wordpress/api-fetch": "^6.48.0",
		"typescript": "^5.0.4"
	}
}
tsconfig.json
{
	"include": [ "./src/**/*" ],
	"compilerOptions": {
		"outDir": "./build/",
		// Per https://www.typescriptlang.org/docs/handbook/modules/theory.html#module-resolution-for-libraries
		"module": "nodenext",
		"moduleResolution": "nodenext"
	}
}
src/index.ts
import apiFetch from '@wordpress/api-fetch';

apiFetch( { path: '/wp/v2/posts' } ).then( ( posts ) => {
	console.log( posts );
} );

Run npm install, then npm exec tsc to attempt to build the "library".

Expected results

Build succeeds

Actual results

src/index.ts:3:1 - error TS2349: This expression is not callable.
  Type 'typeof import("/tmp/test/node_modules/@wordpress/api-fetch/build-types/index")' has no call signatures.

3 apiFetch( { path: '/wp/v2/posts' } ).then( ( posts ) => {
  ~~~~~~~~


Found 1 error in src/index.ts:3

Notes

If we change the apiFetch() call to apiFetch.default(), tsc is happy but then the code won't work when the library is bundled and served to a browser.

To make things work in both environments, we needed to do something like this.

Metadata

Metadata

Assignees

Labels

Good First IssueAn issue that's suitable for someone looking to contribute for the first time[Package] API fetch/packages/api-fetch[Status] In ProgressTracking issues with work in progress[Type] BugAn existing feature does not function as intended

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions