无法将jQuery添加到Angular CLI项目

3

我想在我的angular cli项目中使用jQuery。 我已经尝试了这里的说明:https://www.gurustop.net/blog/2016/11/18/3821/jquery-angular2-angularcli-how-to

  1. Install jQuery

    npm install --save jquery;
    
  2. Install jQuery type defination for type checking.

    npm install --save-dev @types/jquery
    
  3. Add refenece of jquery file in "scripts" array inside angular-cli.json file.

    "scripts": [
       "../node_modules/jquery/dist/jquery.min.js"
    ]
    
  4. Import jquery in my app.component.ts file

    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");
    }
    
然而,当我执行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.

如果我删除 import * as jQuery from 'jquery'; 和 `ng build',那么我会得到:

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

我不确定接下来该怎么做。

更新 1

基于 @Saravana 发布的内容。 如果我只是执行 declare const $: JQueryStaticng build,我会得到以下错误:

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

但是如果我按照Saravana在他第一篇帖子中建议的做法去做,就算他已经删掉了那篇帖子。
import "jquery"; 
declare const $: JQueryStatic;

它能够顺利构建,所以我认为Saravana应该撤回你的帖子。
2个回答

3
自从jQuery库添加了全局变量$和jQuery,你只需要声明变量即可:
var $ = jQuery;
import "jquery"; 
declare const $: JQueryStatic;

0

升级到最新的cli,创建了一个新项目,并将我的位移动到其中,上面概述的指令正常工作。

npm uninstall -g angular-cli

npm cache clean

npm install -g @angular/cli@latest

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接