2

i am a newbie trying to figure out how to use node packages to my web-dev workflow. For example i am trying to test the axios ajax library.

I thought this should be fairly easy but it's driving me crazy.

So in a folder i have an index.html and an index.js file.

I have run "npm init -y" to create a package.json file and then "npm install axios --save". The package has been installed in the node_modules folder and as a dependency in the package.json file.

Now how should i use the library in my index.js file?

I am trying the following in my index.js file (1st line)

import axios from "axios";

In chrome i get: "Uncaught SyntaxError: Unexpected identifier" In firefox: "SyntaxError: import declarations may only appear at top level of a module"

Trying to link the index.js file with type="module" (as i saw in some other topics) didn't help either. I am just getting a bit different errors.

What am i missing?

fractalbit
  • 963
  • 2
  • 12
  • 17

1 Answers1

1

You can not use "import" in client side js files. "Import" is for node js files which runs on server side.

Easiest way to use node module by providing path.

<script src="/node_modules/path_to_dependency/dist"></script>

for more details have a look : How to include scripts located inside the node_modules folder?

iksheth
  • 132
  • 1
  • 9
  • 1
    This is not strictly true. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import https://stackoverflow.com/q/33516906/362536 – Brad Apr 19 '19 at 22:11
  • 1
    Thanks for this. As i said i am a newbie in all this node modules madness trying to figure things out.So if i understand correctly, if i want to use node modules in a classic web app the correct way is to use something like webpack? That has the necessary code to "convert" these modules to a more classic format? – fractalbit Apr 20 '19 at 16:49