meetecho / janode

A Node.js adapter for the Janus WebRTC server
ISC License
98 stars 36 forks source link

Cannot run browser sample due to unix-dgram dependency #39

Closed jeremyjung closed 8 months ago

jeremyjung commented 8 months ago

Hello,

The browser sample cannot successfully run because the unix-dgram package is imported by transport-unix.js. Uncaught ReferenceError: __filename is not defined is printed to the browser console due to unix-dgram's use of __filename.

As a workaround I can comment out the import UnixTransport from './transport-unix.js'; reference in connection.js and successfully run the sample since it does not use unix sockets. Is it possible to run Janode in the browser without modifying its code? This appears to be related: https://github.com/meetecho/janode/issues/16#issuecomment-1274317439.

Thanks!

atoppi commented 8 months ago

Hello @jeremyjung thanks for reporting this. Indeed the patch you mentioned is the cause of the issue.

You should not modify library code to make it run in a browser. As I mentioned in the discussion you linked, I'd try to avoid dynamic imports (e.g. put await import ('./transport-unix.js') under an if condition) in order to detect in the library if the unix-dgram must be imported or not.

What I suggest is to configure a bundler to ignore that import. I'll try to change the bundle.sh example (that runs rollup btw) to make it ignore unix-dgram.

atoppi commented 8 months ago

can you test if https://github.com/meetecho/janode/commit/7b976c92cbb5ab9bcba7ab32c34f8ca8d0823def solves the issue?

jeremyjung commented 8 months ago

That solves the issue, thank you!

I adapted your solution to work with the Vite development server (which uses rollup internally) by using vite-plugin-node-polyfills and memfs. I've included an example config below.

vite.config.js

import { defineConfig } from "vite";
import { nodePolyfills } from "vite-plugin-node-polyfills";
import replace from "@rollup/plugin-replace";
import path from "path";

export default defineConfig({
  // Create empty unix-dgram.js file in the overrides folder to use as an alias
  // This stub is used when using vite dev server (npm run dev)
  // plugin-replace only works when running a production build (npm run build -> npm run preview)
  resolve: {
    alias: {
      "unix-dgram": path.resolve(__dirname, "overrides", "unix-dgram"),
    },
  },
  plugins: [
    replace({
      preventAssignment: false,
      "import UnixTransport from './transport-unix.js'":
        "function UnixTransport() { this.open = _ => Logger.error('unix-dgram unsupported on browsers')}",
      delimiters: ["", ""],
    }),
    nodePolyfills({
      overrides: {
        fs: "memfs",
      },
    }),
  ],
});