DEV Community

Ahmad Faraz
Ahmad Faraz

Posted on

How to fix “require is not defined” in JavaScript / Node.js? How can we run HTML file on server?

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.
Enter fullscreen mode Exit fullscreen mode

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

{}
Enter fullscreen mode Exit fullscreen mode

then run this command http-server

npm i http-server
Enter fullscreen mode Exit fullscreen mode

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"
    }
]
Enter fullscreen mode Exit fullscreen mode

create file src/index.js

import {DATA} from './data.js'
console.log(DATA)
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

update file package.json

{
  "scripts": {
    "start": "npx http-server src/"
  },
  "dependencies": {
    "http-server": "^14.1.1"
  }
}
Enter fullscreen mode Exit fullscreen mode

the run

npm start
Enter fullscreen mode Exit fullscreen mode

Server start

Error should resolved now.

DEMO VIDEO

Thank you!

Top comments (0)