Home > Blockchain >  require() not working in express script with Node
require() not working in express script with Node

Time:03-20

I've been following along with a PERN stack tutorial from YouTube and I've started running into problems with using the require function in the index file for my server application running Node v 17.7.2 with Express 4.17.

The code that's throwing the errors is here:

const express = require("express");
const app = express();
const cors = require("cors");
const routes = require("./routes/jwtAuth")

app.use(express.json());
app.use(cors());
app.use('/auth', myRoutes);
app.get('/', (req, res) =>{
res.send('hello world!');
});
app.listen(process.env.PORT, ()=>
console.log('listening at port 3000'),
);

The error I get is:

const express = require("express");
                ^
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/Nizz0k/Sites/pgpengapi/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

From what I've read this error used to be limited to using require() in frontend code, but after Node v14 can happen in server scripts as well. I have the type set to module. The error seems to be relatively recent, as I've not had any crashing changes when using require in the app up to now.

CodePudding user response:

When you use ES modules (ie. when you set type to module), you need to use the import syntax:

import express from 'express';
  • Related