Fixing "Cannot use import statement outside a module" in Node.js
Problem
When trying to use ES6 import/export syntax in Node.js, you may encounter the error:
SyntaxError: Cannot use import statement outside a moduleThis error occurs because:
- Node.js traditionally used CommonJS modules (
require()/module.exports) - ES6 modules (
import/export) require explicit configuration - The file extension and package.json settings determine which module system is used
Solutions
1. Set "type": "module" in package.json (Recommended)
The most straightforward solution is to add the module type to your package.json:
{
"name": "your-project",
"version": "1.0.0",
"type": "module",
// ... other fields
}After making this change, you can use import/export syntax in all .js files in your project.
INFO
If you omit the "type" field, Node.js defaults to "commonjs" (traditional require/module.exports syntax).
2. Use .mjs file extension
If you don't want to change your package.json, rename your files to use the .mjs extension:
- Change
main.jstomain.mjs - Change
mod.jstomod.mjs
Then run your application with:
node main.mjsWARNING
When using .mjs files, Node won't automatically resolve index.mjs when you specify a directory path. You must explicitly include the full filename.
3. Use CommonJS syntax (legacy approach)
If you prefer not to use ES modules, convert your code to CommonJS syntax:
// mod.js
module.exports.func = function(){
console.log("Hello World");
}// main.js
const myMod = require("./mod");
myMod.func();4. For TypeScript projects
If you're working with TypeScript, you need to compile your code first:
npx tsc file.ts
node file.js5. For testing with Mocha and TypeScript
If you encounter this error during testing, configure your test script:
{
"scripts": {
"test": "cross-env TS_NODE_COMPILER_OPTIONS='{ \"module\": \"commonjs\" }' mocha -r ts-node/register -r src/**/*.spec.ts"
}
}6. For browser usage
In HTML files, add type="module" to your script tags:
<script src="main.js" type="module"></script>If using Babel, configure it appropriately:
<script type="text/babel" data-plugins="transform-es2015-modules-umd" data-type="module"></script>Historical Note
In older Node.js versions (before 13), you needed to use the experimental flag:
node --experimental-modules program.jsThis flag is no longer necessary in modern Node.js versions (14+), as ES module support is stable and fully implemented.
Best Practices
- Use "type": "module" in package.json for new projects
- Keep consistent - don't mix CommonJS and ES modules in the same project
- Update Node.js to the latest LTS version for the best ES module support
- Use explicit file extensions in imports for better reliability
By following these approaches, you can successfully use ES6 import/export syntax in your Node.js applications without encountering the "Cannot use import statement outside a module" error.