Angular 8使用jQuery

Irr*_*der 2 javascript node.js typescript angular angular8

我有一个利用SignalR与桌面应用程序进行通信的应用程序。要使用SignalR,我需要在.ts文件中使用jQuery。但是,从Angular 7迁移到Angular 8后,它似乎不起作用。

我declare var $: any;像以前的Angular版本一样使用。不幸的是,$现在在控制台上显示空白。

那么,Angular v8是否不再支持以这种方式使用jQuery,还是在迁移中出现了其他问题?

更新:

我有通过npm加载的jQuery v3.3.1。

这使其成为全局(在angular.json中)

"scripts": [
         "./node_modules/jquery/dist/jquery.min.js",
         "./node_modules/signalr/jquery.signalR.js"
]
Run Code Online (Sandbox Code Playgroud)

Ton*_*Ngo 8

无需使用更优雅的方式

declare var $: any;
Run Code Online (Sandbox Code Playgroud)

首轮

npm install jquery --save
npm install @types/jquery --save
Run Code Online (Sandbox Code Playgroud)

然后在architect => build.angular.json文件的scripts部分中,为jquery lib添加路径

"scripts": [
  "node_modules/jquery/dist/jquery.min.js"
]
Run Code Online (Sandbox Code Playgroud)

然后在您的tsconfig.app.json中

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["jquery"] // add here
  },
  "exclude": ["test.ts", "**/*.spec.ts"]
}
Run Code Online (Sandbox Code Playgroud)

因此,现在您可以在项目中的任何位置使用jquery,而无需使用declare var $ : any需要使用jquery的每个文件

  • 这太棒了!我不经常在 .ts 文件中使用 jQuery,因此我经常忘记“声明 var $: any;” (2认同)
  • 是的,将其添加到 tsconfig.app.json 中是关键,之前我看到另一个答案将其放入 tsconfig.json 文件中,但这没有帮助。 (2认同)
  • @Stanley 删除yarn-lock 和 package-lock.json 文件,然后再次运行 npm install (2认同)

rob*_*ert 7

Angular 8 适用于 JQuery。

 "dependencies": {
  ...
  "jquery": "^3.4.1",
  ...
}
Run Code Online (Sandbox Code Playgroud)

在您的 angular.json 文件中导入所需的文件,如下所示:

"scripts": [
     "node_modules/jquery/dist/jquery.min.js"
]
Run Code Online (Sandbox Code Playgroud)

./一开始没有,只是node_modules/...

在您的 app.module 中验证它的工作方式如下:

import { AppComponent } from './app.component';

declare var $: any;
console.log(`jQuery version: ${$.fn.jquery}`);

@NgModule({
Run Code Online (Sandbox Code Playgroud)

在开发人员工具控制台中,它应该打印:

jQuery 版本:3.4.1


Irr*_*der 0

因此,在暂时离开这个问题并使用 roberts 答案来确认 jQuery 正在 app.module.ts 中工作(我不知道 console.log 会在导入中间工作)之后,我意识到我已经上次我将 v4 升级到 v7 时遇到了这个问题。

发生的事情是依赖关系导致 jQuery 重新加载。应用程序中启动 signalR 通信的部分还加载另一个依赖项 (telerik-angular-report-viewer),这导致 console.log($) 不显示任何内容,因为 jQuery 尚未加载到组件中。

修复:

删除以下代码

window.jQuery = jQuery;
window.$ = jQuery;
Run Code Online (Sandbox Code Playgroud)

从以下文件中

  • 依赖\telerikReportViewer.kendo.min.js
  • 依赖项\telerikReportViewer.js
  • cjs\telerik-report-viewer.component.js
  • es\telerik-report-viewer.component.js