Ruben
Ruben

Reputation: 515

NodeJS ReferenceError: require is not defined when using supports-color package

I am trying to setup a NodeJS project with babel. Everything seems to be good, However when I import the package 'supports-color' the following error appears:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\me\Desktop\supports-color-test\node_modules\supports-color\index.js

This happend in my main project so that is why I created another project to see if the same error appears again.

Below are the files of my test project.

index.js

import express from "express";
import supportsColor from "supports-color"; // When adding this module the error appears.

const server = express();

if (supportsColor.stdout.has16m) {
  console.log('terminal supports all colors');
}

server.listen(3000, () => {
  console.log('server is running');
})

This is the .babelrc.json file. It does the job unless I try to import my supports-color module in index.js.

{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins":[]
}

And here is a part of package.json where you can see how i compile the code.

"scripts": {
    "build": "babel src --out-dir dist",
    "prestart": "rimraf dist && npm run build",
    "start": "node ./dist/index.js",
  },

I really have no idea why this error keeps comming up. When .babelrc.json is deleted and I use "type": "module" in package.json it does work but then the code is not compiled to CommonJS. So that is not an option.

I also have tried different babel config files but nothing seems to work.

Node version: 14.16.1
NPM version: 6.14.12

Depencies I use:

"dependencies": {
    "express": "^4.17.1",
    "supports-color": "^9.0.2",
    "@babel/cli": "^7.14.5",
    "@babel/core": "^7.14.6",
    "@babel/preset-env": "^7.14.5",
    "rimraf": "^3.0.2"
  }

If more info is needed please let me know.

Upvotes: 1

Views: 802

Answers (1)

Ruben
Ruben

Reputation: 515

Oke so the imported module is referencing to "C:/Users/me/AppData/Local/Microsoft/TypeScript/4.3/node_modules/@types/supports-color/index".

This file says the following: Type definitions for supports-color 8.1

So then I installed supports-color 8.1.1 from npm and now it seems to work.

Upvotes: 1

Related Questions