I assumed at first that it simply means, load the jQuery module and initialize it in a variable called $.
But then, by using Atom with the atom-typescript, I got an error saying that it "Cannot find module 'jquery'". Even though all the code works in the browser, it looks like atom-typescript can't resolve anything looking like import x from y.
Now, looking at ES6 doc, I found out that you import a class/function from a module. The meaning is totally different, and it makes sense with for example this:
import { Component } from 'angular2/core';
But then what does it mean in the case of jQuery?
I am probably mixing different issues in the same one but any explanation would clear this confusion, so thanks a lot in advance :)
The statement import $ from jquery
pretty much amounts to dependency injection. Just like one would write import React from 'react'
to give oneself access to the React library within a file, so to can one write import $ from jquery
. (In case it's throwing you off, the dollar sign is used because jQuery and its methods are accessed using the dollar (a.k.a. jQuery) operator.
As for the errors being thrown, that could be several things:
If you separately installed jQuery as a dependency in your package.json file as well as included a <script>
tag from a jQuery CDN, this error will be thrown. If you're usage of jQuery is through NPM, then the import $ from jquery
syntax is correct/necessary. If you intend to use jQuery through a CDN (as I would recommend), the import
statement is unnecessary. (Since you've included that script tag in your index.html, you have access to jQuery and its library throughout the scope of your application). Do not, however, do both.
Also note that in the case of the import { Component } from 'angular2/core';
statement, something slightly different is going on. Namely, one is importing the named export Component, as per the (AMD specification. You can think of it, in this case, as importing only a part of the larger Angular2 core library when the entire library would be unnecessary.
Just to be sure, check that you have actually given yourself access to jQuery through either a CDN or by installing it as an NPM 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