An imported function won't work in a Node Worker Thread because the dependency graph isn't loaded

I'm trying to use Node's worker_threads using node-worker-threads-pool (a wrapper) package and its DynamicPool.

My issue is that executing a thread giving a function which has imports won't work because that function will be undefined.

// moduleA.js
import xyz from './xyz.js'

const f = x => {
   xyz () //<-- f is undefined
}

export default f

// moduleB.js
import f from './moduleA.js'


f (1) // 

// moduleC.js
const x = await pool.exec ({
   task: f
})

Is this an specific issue of node-worker-threads-pool or Node's worker_threads? Do you know some approach to workaround this issue?


It appears to be a limitation of the library, and has nothing to do with modules:

Notice: If task is a function, you can not use closure in it! If you do want to use external data in the function, you can use workerData to pass some cloneable data.

This sounds a lot like they are stringifying the function and creating a worker from that code only.

Use a worker file instead.