2016-09-20 33 views
1

根据https://angular.io/docs/ts/latest/guide/webpack.html你应该能够在vendor.ts添加厂商如jQuery文件如何使用vendor.ts从https://angular.io/docs/ts/latest/guide/webpack.html

// Other vendors for example jQuery, Lodash or Bootstrap 
// You can import js, ts, css, sass, ... 

我做了什么至今

typings install dt~jquery --global --save 
npm install jquery --save 

,我加入这行vendor.ts

import 'jquery' 

用的WebPack运行出错。但我无法在我的组件中使用jQuery。

import { Component, OnInit, ElementRef } from '@angular/core'; 

@Component({ 
    selector: 'table-widget', 
    templateUrl: 'table-widget.component.html' 
}) 

export class TableWidgetComponent implements OnInit { 

constructor(private _elRef: ElementRef) { 

} 

ngOnInit() : void { 
    $(this._elRef.nativeElement).find('button').on('click', function() { alert("it works"); }); 
} 
} 

我在做什么错在这里?

回答

0

您需要将jQuery公开到全局上下文。

这些选项都可以实现您需要的功能。

在你的WebPack配置:

plugins: [ 
    .... //your other configs 
    new webpack.ProvidePlugin({ 
     jQuery: 'jquery', 
     $: 'jquery', 
     jquery: 'jquery' 
    }) 
] 

或者使用expose-loader

module: { 
    loaders: [ 
     { test: require.resolve("jquery"), loader: "expose?$!expose?jQuery" }, 
    ] 
} 
+0

感谢:-)它的工作原理 – kuerbi