Skip to content

Conditional Node code bundled for browser platform #2852

@elefeint

Description

@elefeint

Is it possible with esbuild to bundle javascript that contains conditionally gated Node code for browser target? Currently, it results in an error message -- The package "module" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error. While switching the target to node would work, it's also not semantically correct and will probably cause more issues in the future, since this bundle really was intended for browser use (we have another bundle being generated from the same source code for the node target).

  if (ENVIRONMENT_IS_NODE) {
    const {createRequire: createRequire} = await import("module");
    var fs = require("fs");
    // ... other code ...
  } else {
    // browser-specific alternative
  }

The reason this came up now is that emscripten 3.1.27 changed the way they output multi-environment javascript to use an explicit import('module'), which caused previously successful esbuild bundling to fail. I've tried setting the treeShaking option, hoping the unused conditional will be pruned, but it did not seem to have an effect.

Minimal reproducer attached.

esbuild_conditional_node.tar.gz

Metadata

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