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:
- latest Node.js
- Add "type": "module" to the package.json
- Add experimental flag when running node.js
node --experimental-modules app.js
But if I add the
"type": "module"
to mypackage.json
file, I can't userequire
statements anymore, because I get aReferenceError: 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"
:
You can still use CJS modules, you just import them via
import
instead ofrequire
(or viaimport()
[dynamic import] if necessary). See details here and here.You can use
createRequire
to effectively get arequire
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 withimport
.
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");