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).
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="./app.js" type="module"></script>
</body>
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.
<body>
<script src="./app.js" type="module"></script>
</body>
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?
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.