I use jQuery-based select2 component in my AngularJS project. I had similar issue as guys here: https://github.com/fronteed/icheck/issues/322, and solved it using advice from there. To be accurate, I received error TypeError: $(...).select2 is not a function
when not using that advice.
i.e. I added next lines to configuration of Webpack in @angular/cli/models/webpack-configs/common.js
.
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
Is it the best possible way to enable jQuery in angular/cli?
I don't think that doing same as in https://github.com/angular/angular-cli/wiki/stories-global-lib is correct way, because
a) webpack bundles jQuery without need to specify it in scripts
b) it still throws TypeError: $(...).select2 is not a function
error when you include it as described in story.
i use jQuery in my project as follows.
Install jQuery
npm install --save jquery
Install jQuery type defination for type checking.
npm install --save-dev @types/jquery
Add refenece of jquery file in "scripts" array inside angular-cli.json file.
"scripts": [
"../node_modules/jquery/dist/jquery.min.js"
]
import jquery in any component you want to use.
import * as jQuery from 'jquery';
that's it. the same way you can also use other libraries like moment.js
, d3.js
etc.
You could also use expose-loader. The example below is written for webpack 2,
{ test: /[\/]jquery\.js$/,
use: [
{ loader: 'expose-loader', query: 'jQuery' },
{ loader: 'expose-loader', query: '$' }
]
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With