Angular CLI:__WEBPACK_IMPORTED_MODULE_1_jquery__(...).collapse 不是一个函数。

10

我有一个通过CLI(Angular 4)生成的Angular应用程序组件。

我这样引入了jQuery + Bootstrap:

  "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "styles.css"
  ],
  "scripts": ["../node_modules/jquery/dist/jquery.min.js",
              "../node_modules/bootstrap/dist/js/bootstrap.min.js"
  ],

我的应用组件长这样:

import { Component, AfterViewInit } from '@angular/core';
import * as $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [

    './app.component.css']
})
export class AppComponent implements AfterViewInit {
  title = 'app';

  constructor() { }

  ngAfterViewInit() {

    $('.nav a').click(function () {
        $('.navbar-collapse').collapse('hide');
    });
  }
}

收到以下错误:

ERROR TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery__(...).collapse is not a function

Bootstrap 没有被正确导入吗? 我尝试在我的组件顶部添加以下内容:

import 'bootstrap/dist/js/bootstrap.js';

编辑:

我注意到一件事情。如果我通过Chrome控制台执行以下代码,则可以在浏览器中运行而无需问题:

$('.navbar-collapse').collapse('hide');

这里会有什么不同呢?我一定漏掉了什么。


2
你尝试过全局声明jquery吗?虽然你会错过类型定义。可以使用以下方式代替: declare var $:any; 而不是: import * as $ from 'jquery'; - Krishnanunni Jeevan
不理解这里的区别是什么? - aherrick
你有没有任何最小化的示例可以重现它? - yurzui
@aherrick。因为Bootstrap需要全局的jquery,所以以下链接可能会有所帮助:https://weblog.west-wind.com/posts/2016/Sep/12/External-JavaScript-dependencies-in-Typescript-and-Angular-2#jQueryandPlugins - Krishnanunni Jeevan
5个回答

27

以下步骤解决了我的问题...

我将组件中的jQuery导入命令替换为

import * as $ from 'jquery';

declare var $ : any;

2
这个变更实际上是做什么的?它对我很有效。只是好奇。 - HexaCrop
今天的英雄! - F3L1X79
你是天才! - Muhammad Noman

6

4
您不应该这样指定您的依赖关系。
因为您已经通过npm / yarn安装了bootstrap和jQuery,所以应该直接导入它们,如import * as $ from'jquery';,不需要配置其他内容。 不需要使用scriptsscripts应该被视为全局脚本,就像index.html内部的脚本标签一样,请参见此处的脚本故事
由于collapse是来自bootstrap的jquery插件,所以您应该执行类似以下操作:
interface JQuery {
  collapse(options?: any): any;
}

为了让TypeScript知道它的类型。

更新 #1

您可以安装@types/bootstrap来跳过定义接口。


我不确定我理解了。接口折叠代码放在哪里?为什么需要它?它不应该无论类型都能工作吗? - aherrick
TypeScript中,类型是最重要的特性。如果TypeScript不知道collapse方法是什么,它会像你一样抱怨它。 - e-cloud

3

请按照以下步骤操作:

1)安装jQuery。(如果已经安装,请跳过此步骤)

npm install jquery --save

2)安装jQuery的类型。

npm install @types/jquery --save

3) 在 app.module.ts 中导入jQuery。

import * as $ from 'jquery';

4)安装Bootstrap 3而不是4,因此请从angular.json中删除任何bootstrap.bundle.min.js

npm install bootstrap@3 --save

5) 在 angular.json 中添加正确的注入,顺序很重要。

"scripts": [
      "node_modules/jquery/dist/jquery.min.js",
      "node_modules/bootstrap/dist/js/bootstrap.min.js"
]

6)在使用 $(element).collapse 的文件中,在导入之后添加以下内容:

    declare var $: any;

7) 现在您可以使用

    $(element).collapse();

1
你可以尝试这样调用jQuery:

    import $ from 'jquery/dist/jquery';

it does not matter - Elvin Garibzade

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