Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use axios with native es6 module? [duplicate]

I use ES6 for a while and have no experience with npm or node.js.

I want to use some npm modules in my project using ES6.

I tried following and got an error

import {axios} from './axios.js';

The requested module './axios.min.js' does not provide an export named 'axios'

I am trying to use https://github.com/axios/axios/blob/master/dist/axios.js

I do not want to use <script src="..."></script> tag implementation. I want to to load it on demand with ES6 modules.

Is there any helper script to adapt npm modules to ES6 or any solution?

like image 960
Zortext Avatar asked Nov 15 '18 10:11

Zortext


1 Answers

import {axios} from './axios.js';

would require Axios to have a named export like

export function axios(...params) { ... }

Axios does have a default export though, which you import without the curly braces:

import axios from './axios.js';

For imports to work in a browser, you need to declare the importing script with type="module":

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

Edit:

Checking that URL you gave it seems Axios does not provide an ECMAScript module at all. Importing the way I described will work as long as you're using something like webpack to bundle your scripts.

Edit 2:

I have just filed an issue on the Axios repository regarding the topic: https://github.com/axios/axios/issues/1879

Edit 3 (April 2021):

Three years forward, even Node.js supports ES Modules, but Axios seems stuck on an old code base that looks unlikely to ever get updated, which causes problems when you want to use Axios along with Vue.js 3/Vite build stack, or Svelte.

A 20% the size but not all the features (e.g. interceptors are missing) rewrite in ES6 including proper exports is available with redaxios.

like image 164
connexo Avatar answered Oct 28 '22 05:10

connexo