What does Cannot use import statement outside a module mean?
Why Node reports it
Node.js supports two module systems: CommonJS, which uses require, and ES modules, which use import and export. By default, a .js file is treated as CommonJS unless the nearest package.json says otherwise. If you write import at the top of such a file, Node raises this syntax error.
In the browser, the same problem appears when a script tag loads a module-style file without type module. The fix is to tell the environment which module style you are using.
- Check package.json for a type field
- Use a .mjs extension for ES module files
- Add type='module' to script tags in browsers
Fixing the setup
For a modern Node project, add "type": "module" to package.json so .js files are treated as ES modules. Then update require calls to import statements and add file extensions in relative imports. Some older libraries only support CommonJS, so check their docs before converting.
If you do not want to change the whole project, rename the file to .mjs or convert only the import lines back to require. Keep one module style per project to avoid confusing errors later.
Some bundlers and test runners also raise this error when their config does not match your file types. Checking the tool's setup docs can save time if the package.json change does not help.
Common mistakes
- Mixing require and import in the same file.
- Changing the package type without updating relative import paths.
