"SyntaxError: import statements can only be at the top level of a module" is the error message that I keep encountering.`

For the complete code, click here: https://github.com/vscodr/axios_issue

After spending some time away from JavaScript working in Python, I decided to come back and try to tackle similar tasks using JS. However, I seem to be stuck at a very basic issue! Despite having Axios installed as a dependency,


  "dependencies": {
    "axios": "^0.19.2"
  }

I'm facing an issue when trying to use axios from the first line of my script:


import axios from 'axios' 
r = axios.get('https://swapi.dev')
console.log(r)

Every time I run this, I get the error message:


Uncaught SyntaxError: import declarations may only appear at top level of a module

Despite trying various ways of calling the script like:

<script type="module" src="/main.js"></script>
<script type="module" src="main.js"></script>
<script type="module" src="./main.js"></script>

Which leads to:


Uncaught TypeError: Error resolving module specifier: axios main.js:1:18

And also trying:

<script src="./main.js"></script>
<script src="/main.js"></script>
<script src="main.js"></script>

Resulting in:

 Uncaught SyntaxError: import declarations may only appear at top level of a module :1:18

Even after referring to relevant documentation such as:

 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

and trying code directly from the documentation without success, I find myself stuck on this issue.


axios.get('https://swapi.dev')
.then(function (response) {

// handle success
   console.log(response);
})
.catch(function (error) {

// handle error
  console.log(error);
})
.finally(function () {

// always executed
});

This seems like an elementary mistake that I am struggling with. The browser error messages are not providing much insight. I suspect it could be related to WEBPACK.

There might be some new changes or updates that have eluded me. This simple problem is frustrating me, and I am seeking help to resolve it.

Currently using a fresh install of Windows and VSCode on a new machine.

Answer №1

It seems like there are a couple of concepts that could use some clarification.

import and export are syntax used for ES Modules (ESM). When working in browsers, you can only utilize this syntax if your script is marked as type="module". However, this brings us to the next important point.

Upon executing npm install --save axios (or yarn add axios), you will receive a package.json file containing {"dependencies": ...}, along with a directory named node_modules where axios and its dependencies are installed. Unfortunately, browsers do not recognize the existence of package.json or node_modules, causing issues when attempting to locate something like axios. A potential solution would involve using a loader such as Systemjs to guide the browser accordingly.

In addition, it's worth noting that not all browsers currently support ESM. This is where bundlers like Webpack, Rollup, Snowpack, etc., prove to be valuable – they not only help resolve ESM imports to actual files within node_modules, but also offer the ability to transpile ESM code into standard ES format, bundle everything into one file for improved performance, and even minify it further. (Webpack, for instance, goes above and beyond by handling various tasks including preparing your morning coffee, baking bread, and constructing a kitchen sink.)

To simplify matters - unless you're feeling particularly adventurous, utilizing a bundler is highly recommended.

For those seeking recommendations, I suggest exploring Vite.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ERESOLVE encountered issues resolving the dependency tree for a project using .NET Core 3.1 and Vue.js framework

I encountered an issue while trying to build my application. The error message is as follows: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class ...

What causes the other array to be affected when one is changed?

Take a look at this snippet of JavaScript code: var x = [1, 2, 3], y = x; y[1] = 3; x; // x === [1, 3, 3] Why does this happen? Why is the value of "x" changing when I update "y[1]"? I tried it in both Firefox and Chrome and got the same result. Th ...

Retrieve a selection of data from the data.json file and mix it up

My webpage has a json data sheet containing multiple objects that I am currently showcasing. { "objects": [ ... ] } In terms of templating: $(function () { $.getJSON('data.json', function(data) { var template = $('#objectstpl') ...

Tips for effectively managing asynchronous tasks

I keep getting different numbers every time my code runs. Can you tell me if I'm doing this the right way? Here's the code: export class GetPlanetsService { url='https://swapi.co/api/planets/?page='; planets:Planet[]=[]; headers: ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

Incorporating traditional Javascript classes for modeling in React development

Can traditional JavaScript classes be utilized in models within the MVC framework while using React, as opposed to relying on Redux or contexts & reducers which may impact reusability? If this approach is feasible, how can we efficiently 'subscribe&ap ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

Retrieving the URL of an image from a webpage's photo gallery utilizing the Facebook Graph API with the help of Javascript

After trying out multiple tutorials, it appears that the latest version of the Graph API has caused some issues with my code. Here is the snippet I am working with: function fetchAlbumImages(){ FB.api( '/760126260690750/photos&ap ...

Can you provide guidance on utilizing OneNote JavaScript APIs to interpret indented paragraphs within OneNote?

I keep a notebook that contains the following entries: https://i.stack.imgur.com/MLdO0.png For information on OneNote APIs, you can refer to this link (paragraph class selected already) https://learn.microsoft.com/en-us/javascript/api/onenote/onenote.p ...

"Converting a standard grammar with recursion and alternations into a regular expression: A step-by-step

A grammar is considered regular if it follows either a right-linear or left-linear pattern. According to this tutorial, this type of grammar possesses a unique property: Regular grammars have a special characteristic: through the substitution of every no ...

What steps can be taken to resolve dependency issues encountered during the installation of Firebase in my project?

I am facing a challenge with my Vite React.js app as I attempt to integrate it with Firebase. Unfortunately, during the installation process, I encounter errors in the terminal. The npm audit report raises concerns like: npm audit report protobufjs 6.10. ...

Attempting to showcase data retrieved from various API calls

I am currently facing an issue where I am retrieving stock/share names from my MongoDB database and attempting to display their prices by making API calls for each of them in my component. However, I am only receiving the price for the last stock. Below i ...

Strange error message regarding ES6 promises that is difficult to interpret

Snippet getToken(authCode: string): Promise<Token> { return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => { if (json["error"]) { return Promise.reject(json); } return new Token ...

What is the process for setting up a Node.js module within the $HOME/bin directory?

The title of this question should give you an idea, but allow me to elaborate... Using npm install -g, I am able to globally install packages which can then be accessed as commands. However, in GNU/Linux, this typically requires root access. So, is there ...

Having trouble uploading the file to IPFS: Encounter an issue with HTTPError: project id is mandatory

Currently in the process of developing a basic DApp for sharing chats, with similarities to Twitter but based on a smart contract. I am utilizing hardhat and running my application on localhost. While implementing the feature for users to upload a profile ...

What steps are necessary to deploy Firebase functions using GitHub actions?

Within my project, a structured folder system is in place that looks like this: dev-internal-web -.firebase -.github -e2e -functions -node_modules -src (misc files) One specific folder I have is named functions, and it contains firebase functions. I aim t ...

How can one smoothly rewind X frames in a video or animation on a webpage without experiencing lag?

For my thesis presentation, I decided to make it available online as a video with custom controls resembling a powerpoint slideshow. The challenge I encountered was with transitions between slides in an animated video. Certain transitions needed to loop fo ...

Looking to display a div with a unique timer?

Is there a way to display different divs with unique classes for specific durations of time? For example, I want one div to show for 2000 ms with the class 'one', then another div to show for 4000 ms with the class 'two', followed by a ...

Simple steps to correct the npm installation of the React list filter

I encountered an issue while trying to install react-list-filter using npm (npm install react-list-filter). The error messages displayed in my console are as follows: npm ERR! code ETARGET npm ERR! notarget No matching version found for <a href="/cdn-c ...

Tips for confirming schedule accuracy

Trying to determine if a specific time falls between two others is the task at hand. Allow me to illustrate: Presently, it's Thursday, and the time reads 11:39 PM. Establishment X operates from 12:00 AM to 11:59 PM on Thursdays (a regular occurrence ...