Why I have the following error require is not defined with express?

Viewed 212

My server.js file return the following error: ReferenceError: require is not defined

server.js:

import express from 'express'
import { readdirSync } from 'fs';

const app = express()

// Route middleware
readdirSync('./routes').map((route) => 
    app.use('/api', require(`./routes/${route}`))
)

const port = 8000

app.listen(port, () => console.log(`listening on port ${port}`))

Note that in my package.json I use: "type": "module" just to use import instead of require.

1 Answers

Your file is ES6 JS, kind of .mjs file; and you're using both import and require (ES5). To use require in ES6 JS code, this module is good: mjs-require

Install mjs-require to use require function in ES6 code:

npm i mjs-require --save

To run .mjs file with require function enabled:

node --experimental-modules -r mjs-require yourfile.mjs
Related