Bootstrap FreeKB - Node.js - Resolve "Cannot use import statement outside a module"
Node.js - Resolve "Cannot use import statement outside a module"

Updated:   |  Node.js articles

This is by far one of the most common errors in Node.js.

Cannot use import statement outside a module

 

Simply put, there are two types of Node.js.

  • CommonJS - uses "require"
  • ES Module - uses "import"

If your package.json file has "type": "module" then you are using a module. Otherwise, you are probably using CommonJS.

{
  "type":"module",
  "dependencies": {
    "@aws-sdk/client-sns": "^3.620.0"
  }
}

 

For example, let's say you are trying to use Express.

If you are using CommonJS, you would "require" Express.

const express = require("express");

 

If you are using ES Module, you would "import" Express.

from express import "express";



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f1b892 in the box below so that we can be sure you are a human.