简体   繁体   中英

Uncaught Reference error require not defined in javascript

Hello i am beginner in JavaScript. I am trying to access the functions of user.js in script.js but it is throwing error i have attached ss also, and below is the implementation of what I am doing.

I have create 4 files

index.js (starting file):

const express = require("express");
const app = express();
const path = require("path");
const { getUserName, getRoomUsers } = require("./utils/user");
const port = process.env.PORT || 3030;
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
app.use("/home", express.static("public"));
app.get("/home/welcome", (req, res) => {
  res.render("home");
});
app.get("/", (req, res) => {
  res.send("Welcomme to startup page!!");
});

app.listen(port);

home.ejs (in /views):

<!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>
    <h1>welcome to home page</h1>
    <script src="script.js"></script>

</body>
</html>

user.js (in /utils):

let user = [];
function getUserName(id, room) {
  const obj = users.find((user) => user.room === room && user.id === id);
  return obj.username;
}
function getRoomUsers(room) {
  return users.filter((user) => user.room === room);
}
function userJoin(id, username, room) {
  const user = { id, username, room };
  users.push(user);
  return user;
}
module.exports = {
  userJoin,
  getRoomUsers,
  getUserName,
};

script.js (in /public):

const { getUserName, getRoomUsers } = require('./../utils/user.js')
getRoomUsers("abcd")

on running this i am getting the following error

在此处输入图片说明

how can i access the user.js functions in script.js

require is not JavaScript native method. Which is of Node.js

Please see: https://stackoverflow.com/a/9901097/16351248

And, you could use native JavaScript method: import

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

require and module.exports are features of CommonJS modules which Node.js supports but browsers do not.

Modern browsers support ES6 modules (which use import and export ) so you could rewrite your modules in that format. MDN has a guide .

Alternatively you could use a tool like Parcel or Webpack to bundle your modules into a single browser-compatible JS file which you can provide to browsers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM