Skip to content

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 module

This 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

The most straightforward solution is to add the module type to your package.json:

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.js to main.mjs
  • Change mod.js to mod.mjs

Then run your application with:

bash
node main.mjs

WARNING

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:

javascript
// mod.js
module.exports.func = function(){
    console.log("Hello World");
}
javascript
// 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:

bash
npx tsc file.ts
node file.js

5. For testing with Mocha and TypeScript

If you encounter this error during testing, configure your test script:

json
{
  "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:

html
<script src="main.js" type="module"></script>

If using Babel, configure it appropriately:

html
<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:

bash
node --experimental-modules program.js

This flag is no longer necessary in modern Node.js versions (14+), as ES module support is stable and fully implemented.

Best Practices

  1. Use "type": "module" in package.json for new projects
  2. Keep consistent - don't mix CommonJS and ES modules in the same project
  3. Update Node.js to the latest LTS version for the best ES module support
  4. 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.