3

I am trying to use axios for a http request in my app.js file, but I always get the error message:

Uncaught SyntaxError: Cannot use import statement outside a module.

I created the js folder, files and other js packages using parcel-bundler and run browser-sync to start the server.

What am I missing? Please help I am new to JavaScript. I am on macOS Big Sur 11.5.1, node v14.17.4

import axios from 'axios'

document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector('form')
    form.addEventListener('submit', async (event) => {
    event.preventDefault()

    const username = document.querySelector('input').value 
    
    const response = 
    await axios.get(`https://api.github.com/users${username}`)
    console.log(response.data)
    })
})
Tamia
  • 41
  • 3
  • Does this answer your question? https://stackoverflow.com/questions/58384179/syntaxerror-cannot-use-import-statement-outside-a-module – Take-Some-Bytes Aug 02 '21 at 05:00

3 Answers3

0

Add "type": "module" to your package.json

{
  // ...
  "type": "module",
  // ...
}

Update:

It should looks like this:

  {
   "name": "githubUser",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "type": "module",
    "scripts": {
         "test": "echo \"Error: no test specified\" && exit 1"
   },
    "keywords": [],
     "author": "",
     "license": "ISC",
     "dependencies": {
      "axios": "^0.21.1"
   }
 }
Rukshan Jayasekara
  • 1,945
  • 1
  • 6
  • 26
  • Thank you for the help. I have tried this answer many times but I still get the same error. I have restarted the project like 3 times now, and still not see where I am going wrong. – Tamia Aug 02 '21 at 12:06
  • @Tamia When restarting, did you delete the parcel cache as well? If not, do that. – Rukshan Jayasekara Aug 02 '21 at 12:50
0

In the closest (from the root of project directory) package.json file, add or update "type" field with a value of "module". It will ensure that all your .js, .ts and .mjs files are interpreted as ES modules.

...
{
  ...
  "type": "module"
  ...
}
...
Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38
0

Where can I add it in this file?

{
   "name": "githubUser",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
    "scripts": {
         "test": "echo \"Error: no test specified\" && exit 1"
   },
    "keywords": [],
     "author": "",
     "license": "ISC",
     "dependencies": {
      "axios": "^0.21.1"
   }
 }
Tamia
  • 41
  • 3
  • I updated my answer. Have a look. BTW this is not an answer to the question. You can add this to your question by editing it instead of posting it as an answer :) – Rukshan Jayasekara Aug 02 '21 at 05:58