Home > Net >  How to use NPM modules in plane javascript and html project?
How to use NPM modules in plane javascript and html project?

Time:03-28

I want to use axios in my simple project but it doesn't work but when I use CDN for axios it works..!!

HERE'S THE MY CODE

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <script type="module" src="./app.js"></script>
</body>
</html>

APP.JS

import {  axios } from ("axios");

const getData = async () => {
  const data = await axios.get("https://swquotes.herokuapp.com/random");
  console.log(data);
};
window.onload = getData();

I want to know ho can i use npm packages directly in my project without react

CodePudding user response:

If you have access to node_modules then you can import it directly from the folder, even though thats dirty and is not recommended.

<script src="node_modules/<your_package>/dist/<entry_file>"></script>

Your problem is a little different, just to narrow it a little down - the browser doesnt understand your import statement as it has to be transpiled with webpack.

import {  axios } from ("axios");

So unless you import directly from CDN or use our dirty shown way of importing it - it wont and should not work

  • Related