When this package would be requested in CJS context, those getters would be invoked only when user's code will actually access them, but in ESM context, ESM loader enumerate all properties which are exported from the package and save result internally, so getter for defaultClient is executed only once and before this client ever initialized.
There is no simple way to fix this, other than don't use late-binding at all. So instead of defaultClient expose a function getDefaultClient()
To workaround the issue, i created a cjs file which is called from my ESM modules with the following content:
Describe the bug
applicationinsights
doesn't work properly in ESM environmentThis issue is possibly a duplicate of https://github.com/microsoft/ApplicationInsights-node.js/issues/1205 but with more details and workaround.
To Reproduce Steps to reproduce the behavior:
"type": "module",
inpackage.json
Add
defaultClient
would be undefined.Expected behavior
defaultClient
should be fulfilledAdditional context This happened because of the differences how native ESM and transpiled to CJS modules works.
If you look to the entry point of the
'applicationinsights'
package you will see:When this package would be requested in CJS context, those getters would be invoked only when user's code will actually access them, but in ESM context, ESM loader enumerate all properties which are exported from the package and save result internally, so getter for
defaultClient
is executed only once and before this client ever initialized.There is no simple way to fix this, other than don't use late-binding at all. So instead of
defaultClient
expose a functiongetDefaultClient()
To workaround the issue, i created a cjs file which is called from my ESM modules with the following content: