Skip to content

WS cannot be built for browser usage with webpack 5+ #2117

Closed
@flashd2n

Description

@flashd2n

Is there an existing issue for this?

  • I've searched for any related issues and avoided creating a duplicate issue.

Description

Hello, I maintain a library which can be used either in the browser or in Node apps. Our code has a simple environment detection and we conditionally require 'ws'. This used to work great prior to WS 8, because the "browser" field in the package.json made sure that when this lib is being bundled for the browser, the ws lib will effectively return a noop.

example snippet for [email protected] package.json:

...
  "license": "MIT",
  "main": "index.js",
  "browser": "browser.js",
  "engines": {
    "node": ">=8.3.0"
  },
...

We upgraded to [email protected] and clients started reporting issues building their React apps with our lib. We traced the issue down to the ws lib, which did not fallback to a noop. The reason for this is the included "exports" property:

example snippet for [email protected] package.json:

...
  "license": "MIT",
  "main": "index.js",
  "exports": {
    ".": {
      "import": "./wrapper.mjs",
      "require": "./index.js"
    },
    "./package.json": "./package.json"
  },
  "browser": "browser.js",
  "engines": {
    "node": ">=10.0.0"
  },
...

Exports has priority over "main" and over "browser", which effectively means that the "browser" field is ignored, resulting in errors like "Module not found: Error: Can't resolve 'stream' in '/Users/flash/Coding/temp/react-empty/node_modules/ws/lib'"

A simple solution is to add "browser" to the "exports" field like this:

...
  "license": "MIT",
  "main": "index.js",
  "exports": {
    ".": {
      "browser": {
        "default": "./browser.js"
      },
      "import": "./wrapper.mjs",
      "require": "./index.js"
    },
    "./package.json": "./package.json"
  },
  "browser": "browser.js",
  "engines": {
    "node": ">=10.0.0"
  },
...

This way bundling ws for the browser will continue to work as pre 8.

ws version

8.12.0

Node.js Version

18.13.0

System

System:
OS: macOS 13.2
CPU: (8) arm64 Apple M1 Pro
Memory: 775.80 MB / 16.00 GB
Shell: 5.8.1 - /bin/zsh

Expected result

I expect that ws would not break the webpack bundling for the browser.

Actual result

Attempting to bundle ws with webpack results in error:

Module not found: Error: Can't resolve 'stream' in '/Users/flash/Coding/temp/react-empty/node_modules/ws/lib'
Did you mean './stream'?

Attachments

No response

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