Skip to content

Error in TypeScript + ESM setup #112

@Frando

Description

@Frando

Hi,
I'm using thread-stream (through pino) in a project that uses TypeScript compiled to ESM modules, running in Node.js.

I'm getting this error when running the project:

file:///path-to-project/node_modules/thread-stream/index.js:50
  const toExecute = bundlerOverrides['thread-stream-worker'] || join(__dirname, 'lib', 'worker.js')
                                                                     ^
ReferenceError: __dirname is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/path-to-project/packages/repco-cli/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at createWorker (file:///path-to-project/node_modules/thread-stream/index.js:50:70)
    at new ThreadStream (file:///path-to-project/node_modules/thread-stream/index.js:224:19)
    at buildStream (file:///path-to-project/node_modules/pino/lib/transport.js:21:18)
    at transport (file:///path-to-project/node_modules/pino/lib/transport.js:110:10)
    at normalizeArgs (file:///path-to-project/node_modules/pino/lib/tools.js:297:16)
    at pino (file:///path-to-project/node_modules/pino/pino.js:86:28)
    at file:///path-to-project/packages/repco-common/src/log.ts:29:20
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at ESMLoader.import (node:internal/modules/esm/loader:526:24)

I could fix the error through a hackish solution for the time being:

import module from 'module'
import p from 'path'
import pino from 'pino'

// Fix thread-stream error due to __dirname
// @ts-ignore
globalThis.__bundlerPathsOverrides = {
  'thread-stream-worker': p.join(
    p.dirname(module.createRequire(import.meta.url).resolve('thread-stream')),
    'lib',
    'worker.js',
  ),
}

const logger = pino()

However, it would be nice if that could be fixed somehow upstream.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions