根据 https://angular.io/docs/ts/latest/guide/webpack.html你应该能够在 vendor.ts 文件中添加像 jquery 这样的供应商
// 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"); });
}
}
我做错了什么?
最佳答案
您需要将 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" },
]
}
关于angularjs - 如何使用 https ://angular. io/docs/ts/latest/guide/webpack.html 中的 vendor.ts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39599997/