I’m trying to use the Keycloak Admin Client library in my Nodejs (Typescript) application, but there's a problem about ES6/CommonJs stuff, which I never really understood (import vs require and mixing things).
Here is a snippet of my source code:
import [... whatever ...]
import KcAdminClient from '@keycloak/keycloak-admin-client';
import { Credentials } from '@keycloak/keycloak-admin-client/lib/utils/auth';
export class Controller {
private kcAdminClient = new KcAdminClient();
[...]
As soon as I run my application, I get the following error:
Error [ERR_REQUIRE_ESM]: require() of ES Module .../node_modules/@keycloak/keycloak-admin-client/lib/index.js from .../server/logic/auth/users.ts not supported.
Instead change the require of index.js in .../server/logic/auth/users.ts to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (.../server/logic/auth/users.ts:10:49)
at m._compile (.../node_modules/ts-node/dist/index.js:791:29)
at require.extensions.<computed> [as .ts] (.../node_modules/ts-node/dist/index.js:793:16) {
code: 'ERR_REQUIRE_ESM'
}
But my code does not use require(), or, at least, I haven't put any “require” string in my source file, so I assume it has something to do with how Keycloak Amin Client library is built and how I'm used to import libraries without really understanding what I am doing. In fact I'm pretty sure I faced the same problem in the past with another library, but I can't remember the solution, allegedly because I did not understand it even at the time...
Following the error message advice I tried to write a dynamic import, but I need to import a class name and all of my clumsy attempts resulted in syntax errors at compile time.
How should I import such libraries? And what is the meaning of "such" in this case?
Side note: two days ago I posted the same question on one of the official Keycloak communities, but no one even tried to comment, so I'm inclined to believe that the root cause does not lie into the library itself.
EDIT after Bench Vue answer:
I tried to add "type": "module"
to my package.json as suggested, but then I got a different error:
TypeError: Unknown file extension ".ts"
which led me to another SO Question, where the accepted and most upvoted answer suggests to remove "type": "module"
from package.json, or alternatively, to add "esModuleInterop": true
to the compilerOptions
in my tsconfig.json, which was already there, but issuing ts-node-esm server/index.ts
in a terminal still yelds the same error (ERR_UNKNOWN_FILE_EXTENSION).