Categories
JavaScript Answers

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

Spread the love

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'.

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 *