应用程序洞察导致 Typescript SPA 出现错误

问题描述 投票:0回答:1

我正在使用 TypeScript 在 VSCode 中开发单页 html 应用程序。

该应用程序运行良好,没有错误,没有警告,我决定添加 Azure Application Insight。

我安装它:npm install --save @microsoft/applicationinsights-web

它在node_modules和@types pplicationinsights下创建了applicationinsights文件夹,还在node_modules@microsoft下创建了几个“applicationinsights-*-js”文件夹。

在添加任何代码之前,我添加了: import { ApplicationInsights } from "@microsoft/applicationinsights-web"。

从那一刻起,tsc 没有显示任何错误,但 VSCode 中的“问题”选项卡显示 121 个错误,大部分是我的主要对象不再被识别,并且应用程序无法启动。

我更新了 tsconfig.json 文件以使用:“target”:“ES2022”,“module”:“ES6”和“moduleResolution”:“node”,但没有帮助。

您能帮我理解一下这个问题吗? 谢谢。

typescript visual-studio-code azure-application-insights
1个回答
0
投票

问题是由于 TypeScript 无法识别已安装包提供的类型。

  • 我创建了一个示例项目
    my-azure-appinsights
    并安装了 TypeScript 作为开发依赖项:
    npm install --save-dev typescript 

这是我的打字稿配置文件:tsconfig.json

{
  "compilerOptions": {
    
    "target": "ES2022",                                  
    "module": "ES6",                                
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,                                      
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

package.json:

{
  "name": "my-azure-appinsights",
  "version": "1.0.0",
  "description": "Azure Application Insights example project",
  "main": "test.ts", 
  "type": "module", 
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/applicationinsights": "^0.20.0",
    "typescript": "^5.2.2"
  },
  "dependencies": {
    "@microsoft/applicationinsights-web": "^3.0.5"
  }
}

test.ts文件:

import { ApplicationInsights } from "@microsoft/applicationinsights-web";

// Initialize Application Insights
const appInsights = new ApplicationInsights({
  config: {
    instrumentationKey: "YOUR_INSTRUMENTATION_KEY",
  },
});

// Start tracking telemetry data
appInsights.loadAppInsights();

// Example event tracking
appInsights.trackEvent({ name: "SampleEvent" });

这里我使用

npx tsc

将打字稿编译为 JavaScript

enter image description here

使用

node test.js
运行应用程序后,我可以获得应用程序中配置的自定义事件日志。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.