使用 angular 在 Webpack 中定义 metisMenu
Define metisMenu in Webpack using angular
我使用 'jhipster' 创建了项目,它是 Angular 4
项目。它使用 Webpack
和 'yarn'。我根据需要安装了 metisMenu
,它在 package.json
文件中。我在 vendor.ts
和 'webpack' 中定义了 metisMenu
,但它显示错误 jQuery(...).metisMenu is not a function
。
我是第一次使用 Webpack
。在 Webpack
中定义它的确切方法是什么?
我直接在 required Component
中导入了 metisMenu
,它解决了我的问题。
感谢 Jeeten Parmar,我能够在我引用它的组件中使用以下代码解决此问题:
import 'metismenu';
...
// you can call this inside ngAfterViewInit() in your component
jQuery('#side-menu').metisMenu();
希望对您有所帮助
如果您将 angular cli 与 angular >2 -> 4 一起使用,您可以在 .angular-cli.json 中这样声明:
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/metismenu/dist/metisMenu.js"
[... others jquery plugin ...]
],
并且在您的组件中,您声明 jquery 如下:
declare let $: any;
您必须使用 ngAfterViewInit 来等待 "dom ready" 事件。最后,您有一个这样的组件:
import {Component, ElementRef, AfterViewInit} from '@angular/core';
declare let $: any;
@Component({
[...]
ngAfterViewInit() {
this.menuElement = this._elementRef.nativeElement.querySelector('#side-menu');
(<any>$(this.menuElement)).metisMenu();
}
小心,如果您像这样导入 jquery:
import * as $ from 'jquery';
$
是jquery的新实例,所以MetisMenu不会在里面实现,jquery对象被global
中的新实例替换
尽情享受吧:)
我使用 'jhipster' 创建了项目,它是 Angular 4
项目。它使用 Webpack
和 'yarn'。我根据需要安装了 metisMenu
,它在 package.json
文件中。我在 vendor.ts
和 'webpack' 中定义了 metisMenu
,但它显示错误 jQuery(...).metisMenu is not a function
。
我是第一次使用 Webpack
。在 Webpack
中定义它的确切方法是什么?
我直接在 required Component
中导入了 metisMenu
,它解决了我的问题。
感谢 Jeeten Parmar,我能够在我引用它的组件中使用以下代码解决此问题:
import 'metismenu';
...
// you can call this inside ngAfterViewInit() in your component
jQuery('#side-menu').metisMenu();
希望对您有所帮助
如果您将 angular cli 与 angular >2 -> 4 一起使用,您可以在 .angular-cli.json 中这样声明:
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/metismenu/dist/metisMenu.js"
[... others jquery plugin ...]
],
并且在您的组件中,您声明 jquery 如下:
declare let $: any;
您必须使用 ngAfterViewInit 来等待 "dom ready" 事件。最后,您有一个这样的组件:
import {Component, ElementRef, AfterViewInit} from '@angular/core';
declare let $: any;
@Component({
[...]
ngAfterViewInit() {
this.menuElement = this._elementRef.nativeElement.querySelector('#side-menu');
(<any>$(this.menuElement)).metisMenu();
}
小心,如果您像这样导入 jquery:
import * as $ from 'jquery';
$
是jquery的新实例,所以MetisMenu不会在里面实现,jquery对象被global
尽情享受吧:)