Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to fix Node.js: SyntaxError: Cannot use import statement outside a module with JavaScript.

In this article, we’ll look at how to fix Node.js: SyntaxError: Cannot use import statement outside a module with JavaScript.

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

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

Conclusion

To fix Node.js: SyntaxError: Cannot use import statement outside a module with JavaScript, we can create and import CommonJS modules.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.