2016-09-20 32 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