0
0
JavascriptDebug / FixBeginner · 3 min read

Fix 'Cannot use import statement outside module' Error in JavaScript

This error happens because JavaScript files are not treated as modules by default. To fix it, add "type": "module" in your package.json or use the .mjs file extension, so the environment knows to handle import statements properly.
🔍

Why This Happens

This error occurs because JavaScript engines treat files as scripts by default, not modules. The import statement only works inside modules. If your environment doesn't know your file is a module, it throws this error.

javascript
import fs from 'fs';

console.log('Reading file...');
Output
SyntaxError: Cannot use import statement outside a module
🔧

The Fix

Tell your environment to treat your file as a module. You can do this by adding "type": "module" in your package.json file or by renaming your file with a .mjs extension. This way, the import statement will work correctly.

javascript
{
  "type": "module"
}

// index.js
import fs from 'fs';

console.log('Reading file...');
Output
Reading file...
🛡️

Prevention

Always configure your project to use modules if you plan to use import and export. Use "type": "module" in package.json or .mjs extensions consistently. Also, use modern tools like bundlers or Node.js latest versions that support ES modules natively.

⚠️

Related Errors

Other similar errors include:

  • SyntaxError: Unexpected token import - Happens in older Node.js versions that don't support ES modules.
  • ReferenceError: require is not defined - Happens when mixing ES modules with CommonJS incorrectly.

Fix these by updating Node.js or using consistent module systems.

Key Takeaways

Add "type": "module" in package.json to enable ES modules in Node.js.
Use .mjs file extension as an alternative to signal module files.
Ensure your environment supports ES modules (Node.js 12+ or modern browsers).
Avoid mixing CommonJS (require) and ES modules (import) in the same file.
Use bundlers or transpilers if targeting environments without native module support.