murat-dogan / node-datachannel

WebRTC For Node.js and Electron. libdatachannel node bindings.
Mozilla Public License 2.0
292 stars 56 forks source link

Support for CommonJS #238

Closed kevglass closed 5 months ago

kevglass commented 6 months ago

I'm currently trying to integrate into an existing code base thats very stuck on CommonJS.

I've worked round the initial round of issues in Jest testing by using babel to convert to CommonJS, remove import.meta etc.

However, I'm now hitting another issues at runtime with a

Error [ERR_REQUIRE_ESM]: require() of ES Module /app/node_modules/node-datachannel/lib/index.js from ...

I'm on Node.js v18.19.0 so I thought this would all be plain sailing.

It'd be really great to have a build that could be use in CJS as well as ECMS. Happy to have a go at it if thats any help.

ptesavol commented 6 months ago

It would also be very helpful to us here at Streamr if a CommonJS version of node-datachannel was available!

@kevglass here is our current hack how to use node-datachannel in our CommonJS typescript project:

// synchronous type import
type NodeDataChannel = typeof import('node-datachannel', { with: { "resolution-mode": "import" } }) 

// declare a global for the dynamic import
declare global {
    var nodeDataChannel: NodeDataChannel
}

// do this once in some async init function of your code

global.nodeDataChannel = await import('node-datachannel')

// now you can use node-datachannel like this in the rest of your code

let connection: NodeDataChannel.PeerConnection | undefined
connection = new nodeDataChannel.PeerConnection(nodeId)
kevglass commented 6 months ago

Hey @ptesavol - really appreciate the solution/hack, I'll try it out in the code base and see how we go.

murat-dogan commented 6 months ago

I think some kind of this will work. Could you please check and tell me, if is it ok? https://github.com/murat-dogan/node-datachannel/pull/240

ptesavol commented 6 months ago

@murat-dogan Yes, we checked the pr, and it seems to work in CommonJS now

kevglass commented 6 months ago

@murat-dogan Worked for me.

murat-dogan commented 5 months ago

Merged