Skip to content

Importing disabled modules leads to build failure #3367

Closed
@jbaiter

Description

When disabling certain dependencies for a browser environment via the browser field in the package.json (supported in esbuild since 0.5.26, #238), esbuild raises an exception when building code that tries to import from the disabled dependency.

The expected behavior would be that the import succeeds, but resolves to an undefined value that can be checked for in client code. This is how Vite and Rollup handle it.

To reproduce, put this in a directory, run npm install and npm run build:

package.json:

{
  "name": "esbuild-disabled-dep",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
      "build": "esbuild index.js --bundle --outfile=./out.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "node-fetch": "^3.3.2"
  },
  "devDependencies": {
    "esbuild": "^0.19.2"
  },
  "browser": {
    "node-fetch": false
  }
}

index.js:

import nodeFetch from 'node-fetch';

let fetchImpl;
if (typeof fetch !== 'undefined') {
    fetchImpl = fetch;
    console.log('Using browser fetch');
} else  {
    console.log('Using node-fetch');
    fetchImpl = nodeFetch;
}

Or clone https://gist.github.com/jbaiter/e830fb9fd5b2de5bc9d8db341c91bf94

Trying to build the example with npm run build raises this error:

❯ pnpm run build

> esbuild-disabled-dep@1.0.0 build /tmp/esbuild-disabled-dep
> esbuild index.js --bundle --outfile=./out.js

✘ [ERROR] No matching export in "(disabled):node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js" for import "default"

    index.js:1:7:
      1 │ import nodeFetch from 'node-fetch';
        ╵        ~~~~~~~~~

1 error
 ELIFECYCLE  Command failed with exit code 1.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions