I am using Angular-CLI (webpack version) for my Angular 2 project and I also need to use jQuery (sadly. In my case, it's a dependency of Semantic-UI and I am using it for handling menu dropdowns).
The way I am using it:
npm install jquery --save
Then listing in it angular-cli.json
file in the scripts
array:
scripts": [
"../node_modules/jquery/dist/jquery.min.js"
]
So it gets included into bundle file and this file is automatically used to root html file:
<script type="text/javascript" src="scripts.bundle.js">
Then declare var $: any;
in files where I need it and it works well.
However there is a problem with ng test
tests, as Karma throws an error $ is not defined
.
jQuery is a small yet feature-rich powerful javascript library that helps to manipulate the HTML DOM with less javascript code. We can use jQuery with Angular. There are some situations you come across while building Angular apps that it's absolutely necessary to use a library like jQuery to get something done.
To run the test, you will only need to run the command ng test . This command will also open Chrome and run the test in watch mode, which means your test will get automatically compiled whenever you save your file. In your Angular project, you create a component with the command ng generate component doctor .
“QUnit is a powerful, easy-to-use, JavaScript test suite. It's used by the jQuery project to test its code and plugins but is capable of testing any generic JavaScript code (and even capable of testing JavaScript code on the server-side).”
This is because the testing html file, provided by Karma, doesn't include the scripts.bundle.js
file as normally served version does.
The solution is easy; you just include same path to the jquery file into karma.config.js
file in project's root folder. This file is available at the root of the project.
In files
array, add the path with watched
flag like this:
files: [
{ pattern: './node_modules/jquery/dist/jquery.min.js', watched: false },
{ pattern: './src/test.ts', watched: false }
]
Karma now should know about the jQuery dependency.
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