Fix 'Cannot use import statement outside module' Error in JavaScript
"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.
import fs from 'fs'; console.log('Reading file...');
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.
{
"type": "module"
}
// index.js
import fs from 'fs';
console.log('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.