The error SyntaxError: Cannot use import statement outside a module appears when you attempt to use ES6-style import in a file that the JavaScript engine doesn’t recognize as a module. This happens either due to incorrect file extensions or missing module configuration.

Understanding Module Systems in Node.js

Node.js supports two primary module systems:

  1. ECMAScript Modules (ESM)
  2. CommonJS (CJS)

Each has its own way of handling imports and exports. Let’s break down how to use them correctly to avoid this error.

1. Using ECMAScript Modules (ESM)

To use import/export syntax, you need to explicitly tell Node.js to treat your code as a module.

Option A: Update package.json

Add the following line to your package.json:

{ "type": "module"
}

This tells Node to treat all .js files as ESM by default.

Option B: Rename Files to .mjs

Alternatively, you can rename your file to use the .mjs extension:

// yourModule.mjs
import { something } from './otherModule.mjs';

Note: If you’re using TypeScript, make sure the module is set to ESNext or ESModule in tsconfig.json.

2. Using CommonJS (CJS)

If your project is using CommonJS (the default in older Node.js versions), you should use require() instead of import.

Example:

// yourModule.js
const something = require('./otherModule.js');

No changes to package.json are needed for this format.

Conclusion

This error usually comes down to mismatched module settings in your project. Fixing it is often as simple as updating your file extensions or config. If issues like this keep slowing your team down, it might be time to hire Node.js developers who can set up your environment the right way from the start.