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

喜夏-厌秋 提交于 2020-02-03 10:04:47

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/40540403/es6-what-does-import-from-jquery-really-means

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!