mrapi
mrapi

Reputation: 6023

Not able to use a jQuery plugin with Angular 4 and Webpack

I'm using Angular 4 with webpack and I'm not able to use a jQuery plugin,with angular cli it works,with webpack not

I've included the plugin in webpack.config.vendor.js

const treeShakableModules = [
   .....
    '@angular/router',
    'zone.js',
    'virtual-keyboard',

If i check the source page at

script src="/dist/vendor.js?v=SsiHzOEk9BPk3CnH6ivS_kkChKmOOxXsB-fFyDO1R8w"></script>

I can find the js plugin code

In my .ts code I have

import * as $ from 'jquery';
....
$('#mycontrol').css('background-color', 'red');// I see the change so jQuery works
(<any>$('#mycontrol')).keyboard();

In console I got this error: $(...).keyboard is not a function

with angular cli works very simple with this code

declare var $: any;
 $('#mycontrol').keyboard();

thanks

Upvotes: 1

Views: 856

Answers (2)

Anouar Mokhtari
Anouar Mokhtari

Reputation: 2173

first you should to add it webpack config :

 plugins: [

        new HtmlWebpackPlugin({
            template: 'src/index.pt'
        }),


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

    ]

after in your component you can import it :

import * as $ from 'jquery';

this is a global solution access to jquery then several options exist.

of course don't forget to install jquery via npm :

npm i --save jquery 

Upvotes: 1

Fateh Mohamed
Fateh Mohamed

Reputation: 21387

you can import it inside your component like this:

import * as $ from 'jquery';

anf of course import jquery.js in angular-cli.json

Upvotes: 1

Related Questions