microsoft / ApplicationInsights-node.js

Microsoft Application Insights SDK for Node.js
MIT License
321 stars 138 forks source link

Importing Application Insights library in ES6 module import format doesn't work #1311

Closed c-amunir closed 2 months ago

c-amunir commented 2 months ago

I am trying to import application insights into a project that uses ES6.

I have the following code:

import * as appInsights from 'applicationinsights';

const connectionString = '[CONNECTION_STRING]'
appInsights.setup(connectionString).start();
appInsights.defaultClient.trackEvent({
   name: 'test'
});

appInsights.defaultClient.flush();

export default appInsights;

Here's the error I am getting: TypeError: Cannot read properties of undefined (reading 'trackEvent')

I am using node.js v18.20.2 (LTS).

I tried to use applicationinsights v3.0.0 but I was getting the same issues as Issue 1310

I ended up having to do 2 fixes: 1) Downgrade to applicationinsights v.2.9.5 2) Do the following code snippet:

import {createRequire} from 'module';
const require = createRequire(import.meta.url);

let appInsights = require('applicationinsights');
const connectionString = '[CONNECTION_STRING]';
appInsights.setup(connectionString).start();
appInsights.defaultClient.trackEvent({
   name: 'test'
});

appInsights.defaultClient.flush();

export default appInsights;

Optimally, I would be using the ES6 import module and not require, as well as be on v3.0.0 of Application Insights. Though being on v2.9.5 is okay as well for the time being while other issues get resolved.

Any guidance would be much appreciated.

Thanks

JacksonWeber commented 2 months ago

@c-amunir Thank you for bringing this to my attention. I've tested the 3.0.1 release with import syntax and it should work. Please give the updated package a try and let me know. Thank you!

c-amunir commented 2 months ago

Hello @JacksonWeber,

Thanks for the prompt response. the 3.0.1 release did fix the issue with the import syntax.

I appreciate the prompt response!

JacksonWeber commented 2 months ago

Closing as the issue was resolved with the latest release.