How to use axios in vanilla Js?

No matter if import or require use, I always get :

what is wrong?

How are you using it? Without knowing a bit more about your setup, there isn’t any way to tell what the issue is.

image

image

Browser doesn’t support import or require. You can use axios globally after you’ve imported it correctly.

Put this line before you import your own script in your html file.

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

Then remove the import axios line in your axious.js file.

1 Like

In the HTML

<script src="/my-script.js" type="module"></script>

In the script

import axios from './axios.js';

...

The script tag in the HTML needs to have the type of module, else the parser will not understand what import is.

The import statement needs to have the full path to the JS file you’re importing (relative paths should be fine): you cannot do import axios from 'axios' because that’s just a string — the browser has no idea if that’s even a file or where that file is.

And if Axios is not written to support ES6 modules, you’re out of luck and need to do what @ghukahr says.

1 Like

Still can’t get it, axios is a module that I npm it, that how it works in react, what the difference in vanilla ?

The browser has no idea what NPM is. It’s a package manager for Node, it’s not connected to JavaScript in general. You need the actual file (which you could use NPM to add to your project, then the path will be something like ./node_modules/axios/dist/axios.js

Edit: It isn’t how it works in React. I assume you have been using something like create-react-app? That is built on top of a thing called Webpack, which allows you to use modules like you do in Node, automatically does the legwork regarding importing, then bundles everything together into a JS file.

As I can see, you uploaded axios to cloud, where you get that file from?

He didn’t upload it, it’s from here: https://cdnjs.com/

I think you’re confusing how you can use modules in a browser (literally import something from './another-module.js' — you tell it where the file you want to use is), and how you use modules if you have the complex tooling needed to automagically use NPM modules then bundle everything up into a single output file.

afaics you may not be able to do this with axios anyway. Because of how it’s been built, it doesn’t look to be compatible with ES6 modules — it works in your React setup because behind the scenes the tooling is magically allowing that incompatible non-standard module format.

Edit: this (the issues you’re running into at the minute), are probably the worst part of frontend development: there is a vast range of tooling to try to deal with it, and it’s all quite fragile and fiddly. It will get better, but as things stand it tends to be very painful.

Wow thank you, I am so noob, sorry for bothering :sweat_smile::sweat_smile: