To fix Node.js: SyntaxError: Cannot use import statement outside a module with JavaScript, we can create and import CommonJS modules.
For instance, we write
mod.js
module.exports.func = () => {
console.log("Hello World");
};
We export the func
function in the mod.js module file.
Then we write
const myMod = require("./mod");
myMod.func();
to call require
to import mod.js.
And then we call myMod.func
, which should log 'Hello World'
.