Angular 6 ReferenceError: $ is not defined error with JQuery

user3701188 picture user3701188 · Jun 11, 2018 · Viewed 36.9k times · Source

I have installed angular 6 with foundation but I am getting an error with JQuery.

Uncaught syntaxerror: unexpected identifier ReferenceError: $ is not defined

In my component, i have

declare var $:any

onNgInit () {
  $(document).foundation()
}

I have all imports in my angular.json

scripts : [
  "node_modules/jquery/dist/jquery.js"
]

I have tried everything I found on the internet but still facing the same error. Also to add this used to work when I was working with Angular 4

Answer

elvin picture elvin · Jul 28, 2018

This is something related to the way ES6 modules isolation works. Loading from the angular.json file is the same as the script tag on an index.html file (the global scope). When you import it on any component you're getting a new local copy, so avoid importing it this way.

To prevent intellisense and compiling issues, create a typings.d.ts file with the following content:

declare var $: any;
declare var jQuery: any;

Now you're ready to go :)