Categories
JavaScript Answers

How to fix Node.js: SyntaxError: Cannot use import statement outside a module error?

Spread the love

To fix Node.js: SyntaxError: Cannot use import statement outside a module error, we use CommonJS modules.

For instance, we write

module.exports.func = () => {
  console.log("Hello World");
};

to define the func function and export it in mod.js.

Then we write

const myMod = require("./mod");
myMod.func();

to call require to require mod.js.

And we call myMod.func to call the function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *