microsoft / ApplicationInsights-node.js

Microsoft Application Insights SDK for Node.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

c-amunir opened this issue · comments

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

@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!

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!

Closing as the issue was resolved with the latest release.