When we are working with plain javaScript, Sometimes we are getting this error on require()
and we are getting the “ReferenceError: require is not defined” error in the browser environment because the require() method is supported in browsers.
There are already multiple solutions on stackoverflow and also we have multiple articles related to that, we can use type="module"
in <script type="module" />
then we can use import
and export
in JavaScript, like you can see stackoverflow here multiple solutions.
but after that if we get another error like
Access to script at 'file:///Users/ahmadfaraz/Documents/app.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.
This error is coming because we are running the HTML file locally and if you are using VS Code IDE there is a HTML live server has an extension for I'm not sure if this could help you or not. But this is my solution how you can solve this above error.
If we run HTML file on server that error can be solved, let's see how can we run HTML file on local server.
Note: Make sure you must have installed node.js
create file package.json
{}
then run this command http-server
npm i http-server
Then you will see in package.json
that you have installed the http-server library.
create file src/data.js
export const DATA = [
{
"id": "1",
"name": "Ahmad"
}
]
create file src/index.js
import {DATA} from './data.js'
console.log(DATA)
create file src/index.html
<!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="./index.js"></script>
</body>
</html>
update file package.json
{
"scripts": {
"start": "npx http-server src/"
},
"dependencies": {
"http-server": "^14.1.1"
}
}
the run
npm start
Error should resolved now.
Thank you!
Top comments (0)