I use VS Code as text editor, and I install jQuery library as local
I make link to my js file(custom.js) like this
In VS Code the auto-import work, which mean the editor can suggest the syntax for me. But the problem is when I try to open the file in browser(index.html with the link to custom.js) it doesn’t work. The error is unexpected identifier
When I deleted the
import 'jquery' part and link the jquery library directly to html file(index.html) then it work. I first guess it because my browser doesn’t support the ES6 syntax, but when I check my chrome is latest version (ver 72)
Can you help me with this problem?
you can install it through npm by using the command line and typing: $ npm install jquery
Or you could add acdn to the html page
In your first suggestion, I did install through npm install, but then I only choose the jquery.js and put the rest on the other directory . So inside my working directory only 3 file: index.html, jquery.js and custom.js. The problem I faced is the
import doesn’t work. This is what question me
you might have to say import “jquery” from “./jquery.js”
I did, but still receive the same error message.
The strangest part is the auto-import function of Visual Studio Code still work, which suggest the function syntax for me when I code. I mean, if
import doesn’t work because some reason like wrong syntax or wrong address, that auto-import function shouldn’t work too. But here it work well on VS Code, but fail on browser.
I guess it’s browser fault, because when I tried to copy code on MDN about export syntax it still doesn’t work. Guess just use jQuery CDN for the time being, since I should start learning jQuery rather than this.
Still, thank you a lot for your advice.
Browsers don’t understand the
import syntax: you need something like parcel, webpack, or browserify to bundle jQuery in with the rest of your JS, then you load that one bundle with a
<script> tag the normal way.
If you’re just using jquery, this is kind of a pain in the butt, so many people just require it the old-fashioned way, with a script tag pointing to the jquery CDN. Any halfway-decent IDE should be able to support either approach (at least WebStorm does)
So basically, the
import syntax is available in ES6 but only legitimate on code. It’s strange why browser doesn’t support it.
Still, thank you a lot for your explanation. You help me understand the reason for it. Other explanation all supposed I used babel or webpack, which I haven’t learnt yet.