Skip to content

Cannot build TS project when targeting Node16 or NodeNext #1589

Closed
@Julien-Marcou

Description

@Julien-Marcou

Describe the bug

When I build my Node.js + Typescript project, I get the following error:

npm run build

> test@0.0.0 build
> tsc

src/index.ts:1:20 - error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("socket.io-client")' call instead.
  To convert this file to an ECMAScript module, change its file extension to '.mts', or add the field `"type": "module"` to '/home/jmarcou/dev/tarot-ai/package.json'.

1 import { io } from 'socket.io-client';
                     ~~~~~~~~~~~~~~~~~~


Found 1 error in src/index.ts:1

To Reproduce

Here is my project:

📂 test/
├── 📂 src/
│   └── 📄 index.ts
├── 📄 package.json
└── 📄 tsconfig.json

index.ts

import { io } from 'socket.io-client';
// nothing else, this is just the minimal repro we need

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "downlevelIteration": true,
    "target": "ES2022",
    "module": "Node16",
    "lib": [
      "ES2022",
      "DOM"
    ]
  },
  "include": [
    "src/**/*.ts"
  ]
}

package.json

{
  "name": "test",
  "version": "0.0.0",
  "scripts": {
    "build": "tsc"
  },
  "private": true,
  "dependencies": {
    "socket.io": "^4.7.2",
    "socket.io-client": "^4.7.2"
  },
  "devDependencies": {
    "@types/node": "^18.17.13",
    "typescript": "^5.2.2"
  }
}

Expected behavior

I expect to be able to import socket.io-client in the same manner as I can import socket.io.

When I import socket.io I don't have any problem:

import { Server } from 'socket.io';

Platform

  • WSL2 / Ubuntu 20.04
  • Node.js v18.17.1

Additional context

Now you might be wondering why am I importing socket.io-client on a Node.js script ?
Well because I want to connect to a socket.io server from my terminal ^^

I know I can switch the module setting in the tsconfig.json from Node16/NodeNext to CommonJS to fix this issue, but I think there might be a configuration problem in socket.io-client that is the root cause of this problem, so I'd rather wait for a proper fix rather than switching to CommonJS

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs investigationThis issue needs further investigations

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions