What are the steps to leverage npm installed packages in my .js files?

I'm new to web development and I'm trying to incorporate node packages into my workflow. Specifically, I'm attempting to test out the axios ajax library.

It seemed like this would be a simple task, but it's proving to be quite challenging.

In my folder, I have an index.html and an index.js file.

I used "npm init -y" to create a package.json file and then installed axios with "npm install axios --save". The package is now in the node_modules folder and listed as a dependency in package.json.

Now, how do I actually use this library in my index.js file?

I tried the following in my index.js file (on the first line):

import axios from "axios";

When I check in Chrome, I get: "Uncaught SyntaxError: Unexpected identifier", and in Firefox: "SyntaxError: import declarations may only appear at top level of a module".

Even when I try linking the index.js file with type="module" (as suggested in other discussions), it still doesn't work and I receive different errors.

What am I missing here?

Answer №1

In client-side JavaScript files, you cannot use the "import" keyword, as it is meant for Node.js files that run on the server side.

An easy way to use a Node module is by specifying the path.

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

For more information, check out: How to include scripts located inside the node_modules folder?

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

Jenkins is left in a state of paralysis as the npm command fails to yield back control to

When using Jenkins to remotely execute a shell command in Linux, the following command is used: npm run develop However, it appears that this command does not return to the terminal as expected, displaying various project information instead. To run the ...

What is the method for determining the size of a WeakMap?

I am working with a WeakMap that looks like the following: let newObj = new WeakMap(); let key1={"a":1}; let key2={"b":2}; let key3={"c":3}; newObj.set(key1,"value1"); newObj.set(key2,"value2"); newObj.set( ...

Implementing automatic number increment in Vue.js forms

I have a field where I can enter numbers <input type="text" class="form-control" id="validationTooltip01" v-model="verse.number" required> After saving the number in the database, I would like it to automatically increment. For example: If I inpu ...

Unable to retrieve the text enclosed between the:: before and after the:: marker

I attempted this using the XPATH finder in Chrome, and it highlighted the element. However, when running my Selenium script, I received the following error: Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: ...

What could be causing the issue of React not showing the messages of "hello" or "goodbye"?

I have a page with a single button that is supposed to display either "hello world" or "goodbye world" when clicked. However, I am facing issues as the messages are not showing up as expected. Below is a screenshot of what the menu items look like when ca ...

When I executed npm run dev in the command prompt, it returned a SyntaxError

I wanted to develop a login and registration system using Laravel. I followed these steps: composer require laravel/jetstream php artisan jetstream:install livewire npm install npm run dev However, when I ran npm run dev, I encountered the following Synt ...

What are the steps to retrieve information from your personal server using Astro?

I have successfully set up a NodeJS server using Express and Astro for the frontend, with SSR configured through the Astro adapter for NodeJS. My current challenge is fetching data from the backend, and I am unsure of the correct approach to do so. Below ...

Exploring JavaScript and Node.js: Deciphering the choice of prototype.__proto__ = prototype over using the

Currently exploring the Express framework for node.js and noticed that all the inheritance is achieved through: Collection.prototype.__proto__ = Array.prototype; Wouldn't this be the same as: Collection.prototype = new Array; Additionally: var ap ...

The validation error occurred with the expectation of a primitive boolean value

My starting point: I'm completely new to using booleans as a beginner developer snippet of code: const { SlashCommandBuilder, PermissionFlagsBits, PermissionsBitField, EmbedBuilder, } = require("discord.js"); const { ...

Having trouble executing a React Native project because of react-native-gesture-handler

After adding react-navigation and react-native-gesture-handler to my project, I encountered an error when running it with react-native run-android: What's the issue: Could not compile settings file 'C:\Users\pc\Desktop\GST ...

Unable to establish SocketIO callback from client to server resulting in a null object instead

I'm encountering an unusual issue with SocketIO. On the server-side, I am using the emit() method like this: $s.sockets.emit(scope, {some: datas}, function(feedback) { console.log('received callback'); } ) ...

What could be the reason for the message "the project was initialized with an outdated and unsupported version of tools" while running npx create-react-app?

After transitioning to Ubuntu, I started encountering an issue every time I tried to create a React app. The note mentioned that the app being created was a class component. ankit@gram:~/Documents/Development/React/react-project$ npx create-react-app my-ap ...

The React.js .map function encountered an error while trying to map the results from Firebase

As a newcomer to the realm of React and Firebase, I find myself struggling with arrays and objects. It seems like the way my data is formatted or typed does not play well with the .map method. Despite scouring Stack Overflow for answers, none of the soluti ...

Having trouble finding the right path. Is there an issue with Angular routing?

After successfully creating a simple application, I decided to write test cases for it. My first attempt was to work on the routing part of the application. Check out the code on StackBlitz The routing code snippet is as follows: Main module: export cons ...

The && operator is not executed when the button is disabled

There is a button on the page that has been disabled using the [disabled] property. <button class="btn btn-primary center-block" (click)="sign(sf.value)" [disabled]="validateInsuredFirstName(firstName.value) && validateInsuredLastName(l ...

Encountering an npm package resolution error despite following all of the necessary requirements

error message: ERESOLVE Unable to resolve dependency Issues encountered while resolving: @ionic/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52333c35273e332012657c667c60">[email protected]</a> Found: <a href ...

Unable to open new window on iOS devices using $window.open

alertPopup.then (function(res) { if(ionic.Platform.isAndroid()) { $window.open('android_link_here', '_system') } else if(ionic.Platform.isIOS()) { $window.open('ios_link_here', '_system& ...

Create a placeholder for the module function

Update: Providing more specific details. Our team has developed a Github API wrapper extension and we are looking to test different use cases for it. However, we prefer not to use the API wrapper extension directly during testing and instead want to stub ...

The v-menu closes before the v-list-item onclick event is detected

I have set up the following menu using vue and vuetify: <div id="app"> <v-app id="inspire"> <div class="text-center"> <v-menu> <template v-slot:activator="{ on }"> ...

Error in Vue.js and Socket.io - the server response cannot contain the wildcard '*' when the request has its credentials mode set to 'include'

I'm currently working on creating a chat app using Vue and Socket IO. Here's the error I'm encountering. This is my Node server code. And this is my Vue app code. My Node server and Vue app are separate entities. How can I resolve this i ...