Uploaded image for project: 'Node.js Driver'
  1. Node.js Driver
  2. NODE-3527

BSON npm package does not work when using as a ESM

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Blocker - P1 Blocker - P1
    • bson-4.5.0
    • Affects Version/s: None
    • Component/s: None
    • 5
    • Not Needed

      What problem are you facing?

      The BSON node module does not work when using with Vite which transforms it straight from a native ESM module to JavaScript.

      What driver and relevant dependency versions are you using?

      I have faced this problem in version 4.4.0 and also 4.4.1 of the package.

      Steps to reproduce?

      • Start a new project following Vite's instructions here: https://vitejs.dev/guide/
      • Install "bson" as a node package.
      • Import it anywhere in the application (for example in the entry file), I don't think it's necessary to call any methods on the imported object, but just in case we are importing as such:

      import * as BSON from 'bson';

      • Later we call "deserializeStream" like so:

      BSON.deserializeStream(...);

      • Boot up the local server with "npm run serve" or just "vite" in a terminal

      If you wait long enough for it load all the bundles (you can monitor the Network tab on the Chrome Dev Tools) you should see that nothing starts and you will spot this specific console error:

      browser.js:165 Uncaught (in promise) ReferenceError: global is not defined
      at browser.js:165

      Upon further inspection it seems the problem is in the following package:

      http://localhost:8080/core/node_modules/bson/node_modules/process-es6/browser.js

      The offending line 165 in that file "browser.js" contains the following:

      var performance = global.performance || {}

      Well, this can never work because we are deploying our application in the browser so there is no "global" variable. In a browser environment "window" is the global context, whereas in a node environment there is a "global" variable that provides access to the global context which this package is assuming it will always run on.

      This is not necessarily your fault but the package being referenced ("process-es6") is extremely old (last update was 5 years ago) so I cannot reasonably expect them to do anything about it, hopefully you will be able to help me instead!

      Thank you!

            Assignee:
            neal.beeken@mongodb.com Neal Beeken
            Reporter:
            tmagdev@gmail.com Tiago Magalhães
            Daria Pardue
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: