Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import via a URL using ES modules?

I want to import a library like axios directly from a URL and use it.

I don't want to add it as a script which adds axios to the window object (as shown below).

index.html
<body>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="./app.js" type="module"></script>
</body>
app.js
console.log(window.axios !== undefined); // true
const { data } = await axios.get(
  "https://jsonplaceholder.typicode.com/users/1"
);
console.log(data.username); // Bret

I want something like this wherein I can import axios directly from a URL.

index.html
<body>
    <script src="./app.js" type="module"></script>
</body>
app.js
import axios from "https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js";

console.log(window.axios !== undefined);
const { data } = await axios.get(
  "https://jsonplaceholder.typicode.com/users/1"
);
console.log(data.username);

Obviously this doesn't work because the JavaScript code delivered by the above CDN is not meant to be used with ES modules. Is there a workaround?


2 Answers

You can use Skypack:

import axios from 'https://cdn.skypack.dev/axios';

const { data } = await axios.get(
  "https://jsonplaceholder.typicode.com/users/1"
);
console.log(data.username);

Remove the jsDelivr CDN link.

like image 153
Shivam Avatar answered Feb 03 '26 23:02

Shivam


JS file provided by CDN(like yours: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js) will not provide an ES6 module export. Download and search "export default", nothing will be found.

If you use npm, you can add axios to your dependencies and use axios by import axios from 'axios'

If you still want to use ES module with CDN, This article may help.

like image 41
KaMui Avatar answered Feb 04 '26 00:02

KaMui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!