require() not working in module type nodejs script

Usually you need Babel to transpile your Node.js code that uses ES Modules.

But if you don't want to use Babel: ES Modules is experimental feature of latest Node.js.

You need 3 things:

  1. latest Node.js
  2. Add "type": "module" to the package.json
  3. Add experimental flag when running node.js node --experimental-modules app.js

But if I add the "type": "module" to my package.json file, I can't use require statements anymore, because I get a ReferenceError: require is not defined error.

Right. It's either/or. Either you use ESM (JavaScript modules, type = "module") or you use CJS (CommonJS-like Node.js native modules, require).

But, if you're using type="module":

  1. You can still use CJS modules, you just import them via import instead of require (or via import() [dynamic import] if necessary). See details here and here.

  2. You can use createRequire to effectively get a require function you can use in your ESM module, which brings us to...

Why I would need this, is because I want to require some config files based on dynamic paths, and only if the files exists, which I think I can not do with import.

That's right. You have to use createRequire for that instead (or readFile and JSON.parse), more here.

createRequire version:

import { createRequire } from "module";
const require = createRequire(import.meta.url);
const yourData = require("./your.json");