【问题标题】:Unable to add jQuery to an angular cli project无法将 jQuery 添加到 Angular cli 项目
【发布时间】:2017-11-19 11:08:38
【问题描述】:

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

  1. 安装 jQuery

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

    npm install --save-dev @types/jquery
    
  3. 在“scripts”数组里面添加jquery文件的引用 angular-cli.json 文件。

    "scripts": [
       "../node_modules/jquery/dist/jquery.min.js"
    ]
    
  4. 在我的 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");
    }
    

但是,当我执行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 你应该回复你的帖子。

【问题讨论】:

    标签: jquery typescript angular-cli


    【解决方案1】:

    由于 jQuery 库添加了全局变量 $jQuery,您只需声明变量即可:

    import "jquery"; 
    declare const $: JQueryStatic;
    

    【讨论】:

      【解决方案2】:

      升级到最新的 cli,创建了一个新项目,并将我的部分移入其中,上面概述的说明运行良好。

      npm uninstall -g angular-cli
      
      npm cache clean
      
      npm install -g @angular/cli@latest
      

      【讨论】:

        猜你喜欢
        • 2017-11-15
        • 1970-01-01
        • 1970-01-01
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        相关资源
        最近更新 更多