Angular 6 ReferenceError:$未定义JQuery错误

use*_*188 12 jquery zurb-foundation zurb-foundation-6 angular

我已经安装了角度6与基础,但我得到一个错误与JQuery.

未捕获的语法错误:意外标识符ReferenceError:$未定义

在我的组件中,我有

declare var $:any

onNgInit () {
  $(document).foundation()
}
Run Code Online (Sandbox Code Playgroud)

我在angular.json中有所有导入

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

我已经尝试了我在互联网上找到的所有内容,但仍面临同样的错误.当我使用Angular 4时,还要添加这个用于工作

elv*_*vin 8

这与ES6模块隔离的工作方式有关.从angular.json文件加载与index.html文件(全局范围)上的脚本标记相同.当您在任何组件上导入它时,您将获得一个新的本地副本,因此请避免以这种方式导入它.

要防止智能感知和编译问题,请创建typings.d.ts包含以下内容的文件:

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

现在你准备好了:)


kar*_*luS 7

如果您安装了 jquery 并且仍然收到此错误。在您使用的每个组件中$,在顶部添加import * as $ from "jquery";


Bli*_*ard 5

安装Jquery插件For angular

npm install jquery-保存

现在app.module.ts添加

从“ jquery”导入*作为$;

它将使工作完成。


Moh*_*xit 5

始终注意 angular.json 中默认有两个“脚本”部分。大多数开发人员随便在“脚本”标签中给出这样的引用......

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

无需验证他们是否将其添加到测试“脚本”或“构建”脚本...

但是,只需验证一次您将其添加到“构建”部分而不是 angular.json 的“测试”部分,因为这是开发人员经常犯的愚蠢错误。

错误的:

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

对:

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

希望这可以帮助!


小智 0

确保你的路径是正确的?

试试这个[../node_modules/jquery/dist/jquery.js]

  • Angualar 6 中的路径已更改,您编写的路径不再起作用 (3认同)