Hello everyone I am a beginer in web development. I am making a project where in I need to use a npm package npm i link-preview-js
in javascript file with html file and run it in browser
random.js file
import { getLinkPreview, getPreviewFromContent } from "link-preview-js";
// pass the link directly
getLinkPreview("https://www.youtube.com/watch?v=MejbOFk7H6c").then((data) =>
console.log(data)
);
html file
<!DOCTYPE html>
<html lang="en">
<head>
<script src="random.js"></script>
<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></body>
</html>
I am getting an error Uncaught SyntaxError: Cannot use import statement outside a module (at random.js:1:1)
I know i am an begginer their might be a silly error but please could you help me resolve it Thanks in Advance.
CodePudding user response:
import
is a feature of ES6 modules (and TypeScript modules).
While browsers do support it:
- they only do so if you declare your script to be a module
- they do not support Node.js style module resolution and require a URL which is either absolute, or starts with a
/
or a.
.
It is more typical to use modules in combination with a bundler such as Webpack or Parcel.
That said, you need to read the documentation:
You cannot request a different domain from your web app (Browsers block cross-origin-requests). If you don't know how same-origin-policy works, here is a good intro, therefore this library works on node (back-end environments) and certain mobile run-times (cordova or react-native).
You might consider creating a webservice using Node.js and Express.js then accessing it with Ajax from your client side code.
CodePudding user response:
You can convert your file into a module or use the require syntax For the first solution please add :
{
"type": "module"
}
in your package.json file. I hope it solves your issue!