
Fix 'Cannot use import statement outside a module' in Node.js
Fix 'Cannot use import statement outside a module' in Node.js If you've ever tried to use ES modules in Node.js and been greeted with this error: SyntaxError: Cannot use import statement outside a module You're not alone. This is one of the most common errors developers encounter when modernizing their Node.js codebase. The good news? It's incredibly easy to fix. Let me show you exactly how. Why This Error Happens Node.js has been around since 2009, and for most of its history, it used CommonJS as its module system. You're probably familiar with it: // CommonJS - the old way const express = require ( ' express ' ); const { something } = require ( ' ./myModule ' ); module . exports = myFunction ; But modern JavaScript uses ES modules (ESM): // ES Modules - the modern way import express from ' express ' ; import { something } from ' ./myModule.js ' ; export default myFunction ; The problem? By default, Node.js treats .js files as CommonJS modules. When it sees an import statement in a Co
Continue reading on Dev.to Tutorial
Opens in a new tab


