Javascriptservices: Angular2 - Problem running jquery, $ is not defined

Created on 26 Nov 2016  路  6Comments  路  Source: aspnet/JavaScriptServices

I'm trying to use jquery in my app. Previoulsy in rc-4 i would just declare var $: any; and then call it on after OnInit, but when i try to do this in my rc-5 build, it throws $ is not defined.

Component

import { Component, OnInit } from '@angular/core';
declare var $: any;

 @Component({
    selector: 'nav-menu',
    templateUrl: './navmenu.component.html',
    styleUrls: ['./navmenu.component.css']
})
export class NavMenuComponent implements OnInit {
    ngOnInit() {
        // Initialize collapse button
        $(".button-collapse").sideNav();
    }
}

Error

EXCEPTION: $ is not defined  vendor.js:5364:14
ORIGINAL STACKTRACE:  vendor.js:5369:18
[30]/NavMenuComponent</NavMenuComponent.prototype.ngOnInit@http://localhost:5000/dist/0.9ef51c72ff32ccd5ee38.hot-update.js:71:10
anonymous/_View_AppComponent0.prototype.detectChangesInternal@AppComponent.ngfactory.js:86:58
vendor_e1c95acbfa6e50db68d4</</</AppView</AppView.prototype.detectChanges@http://localhost:5000/dist/vendor.js?v=FG8DMO6mAWOeL29rrZABZrd79JSnjdqetNbUsSmBST0:11464:14

Most helpful comment

I'm not 100% certain what you're doing with the <script> tags that isn't working, but if you want to reference jQuery the 'correct' TypeScript+Webpack way (with proper bundling, type checking, etc.), here's how to do so:

  1. Install both jQuery and its type definitions (npm install --save jquery @types/jquery)
  2. In any TypeScript file, you can now add at the top: import * as $ from 'jquery';. Now you can use $ in that file and will get correct intellisense, etc.

Please note that it's not great practice to use jQuery directly in an Angular 2 app, both because it will prevent you from doing server-side prerendering (jQuery can only run in browsers), and it bypasses all the Angular 2 APIs that are meant to be in control of updating the DOM. If you choose to go ahead and use jQuery directly anyway, you'll be on your own in terms of keeping the document state consistent :)

All 6 comments

Seems to be caused by the fact jquery i not loading for some reason.

I'm reopening this because i tried added a script tag on the page, but that doesn鈥檛 throw any errors in the console and bootstraps seems to displaying fine. The weird thing is code inside the script tags doesn't execute at all. I ran it in the console, it returns that jQuery is not loading. Do i have to do something special load jQuery into the the window and/or starter project ?

Script tag

<script>
window.onload = function() {
    if (window.jQuery) {  
        // jQuery is loaded  
        alert("Loading");
    } else {
        // jQuery is not loaded
        alert("Not loading");
    }
}
</script>

Console

Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.  vendor.js:12269:10
[HMR] connected  main-client.js:662:23
GET 
http://localhost:5000/dist/vendor.css [HTTP/1.1 200 OK 0ms]
[HMR] bundle rebuilding  main-client.js:732:25
[HMR] bundle rebuilt in 546ms  main-client.js:736:10
[HMR] Checking for updates on the server...  main-client.js:1791:23
GET 
XHR 
http://localhost:5000/dist/91961c19dfa08071396b.hot-update.json [HTTP/1.1 200 OK 333ms]
GET 
http://localhost:5000/dist/0.91961c19dfa08071396b.hot-update.js [HTTP/1.1 200 OK 143ms]
[HMR] Updated modules:  main-client.js:1864:10
[HMR]  - ./ClientApp/app/components/home/home.component.html  main-client.js:1866:12
[HMR]  - ./ClientApp/app/components/home/home.component.ts  main-client.js:1866:12
[HMR]  - ./ClientApp/app/app.module.ts  main-client.js:1866:12
[HMR]  - ./ClientApp/boot-client.ts  main-client.js:1866:12
[HMR] App is up to date.

I'm not 100% certain what you're doing with the <script> tags that isn't working, but if you want to reference jQuery the 'correct' TypeScript+Webpack way (with proper bundling, type checking, etc.), here's how to do so:

  1. Install both jQuery and its type definitions (npm install --save jquery @types/jquery)
  2. In any TypeScript file, you can now add at the top: import * as $ from 'jquery';. Now you can use $ in that file and will get correct intellisense, etc.

Please note that it's not great practice to use jQuery directly in an Angular 2 app, both because it will prevent you from doing server-side prerendering (jQuery can only run in browsers), and it bypasses all the Angular 2 APIs that are meant to be in control of updating the DOM. If you choose to go ahead and use jQuery directly anyway, you'll be on your own in terms of keeping the document state consistent :)

@SteveSandersonMS Any reason why i shouldn't load Jquery locally from a libs folder in wwwroot ? Does that mean that Jquery gets loaded twice ?

@AndrewKralovec You can certainly do that if you want. It just means it wouldn't be part of your Webpack build pipeline, so you wouldn't automatically get the bundling/minification/multiversioning/etc.

@SteveSandersonMS Thanks as always. I was going to use a JavaScript module that requires jQuery to be loaded. I found that loading it locally worked.

Off topic, but I found your blog and I enjoy it very much. I read that you go to tech conferences and i was wondering if any of them take place in Illinois ? Maybe they are online somewhere ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dantheman999301 picture dantheman999301  路  4Comments

natemcmaster picture natemcmaster  路  4Comments

asadsahi picture asadsahi  路  3Comments

justinyoo picture justinyoo  路  3Comments

raberana picture raberana  路  3Comments