Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6: What does "import $ from 'jquery'" really means?

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 :)

like image 747
TigrouMeow Avatar asked Oct 17 '22 22:10

TigrouMeow


1 Answers

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:

  1. 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.

  2. 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.

like image 148
IsenrichO Avatar answered Oct 21 '22 05:10

IsenrichO