Uncaught ReferenceError: $ is not defined?

One day my junior developer came to me and asked, hey Apoorva I am trying to use jQuery in my Angular4 project but due to some reason getting this “$ is not defined” error. So can you please suggest some pointers, how to fix “Uncaught ReferenceError: $ is not defined?” error in Angular4.

I smiled and recollected that day when I spend my whole day to resolve this jQuery plugin error. This error occurs due to a missing installation of your typescript jQuery plugin.

Here are a few steps which will help you to resolve “Uncaught ReferenceError: $ is not defined?” error :

  1. Make sure you have installed jQuery dependency to your Angular project

    $npm install jquery  –save

  2. Install jQery Typescript dependency to recognize jQuery notations

    $npm install @type/jquery –save-dev

  3. Add path into angular-cli.json for a jquery.min.js file as given below
    "scripts": [
    "../node_modules/jquery/dist/jquery.min.js"
    ]
    
  4. Check package.json file and make sure following dependency added to your JSON
    dependencies
    "jquery": "^3.2.1",
    

    if not please manually add it.

  5. Now clean and build your Angular project to ignore any compilation error.
  6. After following above 4 steps you need to write following line to your typescript files to import jQuery
    import * as $ from “jquery”;

Example

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';

export class JqueryComponent implements OnInit {

constructor() {
}

ngOnInit() {
$(window).click(function () {
alert('welcome to ease2code.com');
});
}

}

Speak Your Mind

*