NodeJS (Server): ReferenceError: require is not defined when type: module

As the documentation says:

No require, exports, module.exports, __filename, __dirname
These CommonJS variables are not available in ES modules.

https://nodejs.org/api/esm.html#esm_no_require_exports_module_exports_filename_dirname

You can't use both natively. If you want to do that use Babel to transpile your code.


ES Modules in Node >= 14 do not support require.

However if you want to add it, u have to add this at the top of your file: Everything should work fine.

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

Several points:

  1. Use .mjs instead of .js.
  2. Never use require.
  3. It is optional to use "type": "module".