简体   繁体   English

无法将jQuery添加到角度cli项目中

[英]Unable to add jQuery to an angular cli project

I want to use jQuery in my angluar cli project. 我想在我的angluar cli项目中使用jQuery。 I have tried the instructions here: https://www.gurustop.net/blog/2016/11/18/3821/jquery-angular2-angularcli-how-to 我在这里尝试了这些说明: https//www.gurustop.net/blog/2016/11/18/3821/jquery-angular2-angularcli-how-to

  1. Install jQuery 安装jQuery

     npm install --save jquery; 
  2. Install jQuery type defination for type checking. 安装jQuery类型定义以进行类型检查。

     npm install --save-dev @types/jquery 
  3. Add refenece of jquery file in "scripts" array inside angular-cli.json file. 在angular-cli.json文件中的“scripts”数组中添加jquery文件的refenece。

     "scripts": [ "../node_modules/jquery/dist/jquery.min.js" ] 
  4. Import jquery in my app.component.ts file 在我的app.component.ts文件中导入jquery

     import { Component } from '@angular/core'; import * as jQuery from 'jquery'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'app'; test = jQuery("body"); } 

However, when a do a ng build I get the following error: 但是,当做一个ng build我收到以下错误:

ERROR in ./src/app/app.component.ts (2,25): Module ''jquery'' resolves
to a non-module entity and cannot be imported using this construct.

If I remove the import * as jQuery from 'jquery'; 如果我import * as jQuery from 'jquery';删除import * as jQuery from 'jquery'; and `ng build' I get: 和'ng build'我得到:

ERROR in ./src/app/app.component.ts (10,10): Cannot find name 'jQuery'.

Not sure where to go from here. 不知道从哪里开始。

Update 1 更新1

Based on what @Saravana posted. 基于@Saravana发布的内容。 If I just do declare const $: JQueryStatic and ng build , I get the error: 如果我只是declare const $: JQueryStaticng build ,我得到错误:

ERROR in ./src/app/app.component.ts (2,19): Cannot find name 'JQueryStatic'.

but if I do what Saravana suggested on his first post before he deleted it. 但如果我在他删除它之前做了Saravana在他的第一篇文章中提出的建议。

import "jquery"; 
declare const $: JQueryStatic;

It builds without complain. 它建立没有抱怨。 So I think Saravana you should revert your post back. 所以我认为Saravana你应该回复你的帖子。

Since the jQuery library adds a the global variables $ and jQuery , you can just declare the variable: 由于jQuery库添加了全局变量$jQuery ,因此您只需声明变量:

import "jquery"; 
declare const $: JQueryStatic;

Upgraded to the latest cli, created a new project, and moved my bits in and the instructions outlined above worked just fine. 升级到最新的cli,创建了一个新项目,并移动了我的位,上面提到的说明工作得很好。

npm uninstall -g angular-cli

npm cache clean

npm install -g @angular/cli@latest

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM