简体   繁体   中英

Angular 2 - Use external library with jquery

I'm using Angular 2 with jQuery and it works well. I'd like to use some external libraries like masonry-layout but i have a problem:

jQuery(...).masonry() is not a function

I use webpack to get JQuery work.

new ProvidePlugin({
    jQuery: 'jquery',
    $: 'jquery',
    jquery: 'jquery',
  })

test.component.ts

import { Component } from '@angular/core';

import 'masonry-layout';

@Component({
    selector: 'test',
    template: `
        <div class="container-fluid grid">
            <div class="grid-item">...</div>
            <div class="grid-item">...</div>
            <div class="grid-item">...</div>
            <div class="grid-item">...</div>
        </div>
    `
})
export class TestComponent {
    ngOnInit() {
        jQuery('.grid').masonry();
    }
}

Any suggestion ? Thanks !

Firstly you should change your import to:

import 'masonry-layout/dist/masonry.pkgd';

Seems configuration changes don't work for this library:

new webpack.ProvidePlugin({
  jQuery: 'jquery',
  $: 'jquery',
  jquery: 'jquery',
  'window.jQuery': 'jquery' <== this line
}),

在此处输入图片说明 So you can try the following:

window.jQuery = jQuery;
import 'masonry-layout/dist/masonry.pkgd';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM