Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditional Node code bundled for browser platform #2852

Closed
elefeint opened this issue Jan 19, 2023 · 2 comments
Closed

Conditional Node code bundled for browser platform #2852

elefeint opened this issue Jan 19, 2023 · 2 comments

Comments

@elefeint
Copy link

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

@evanw
Copy link
Owner

evanw commented Jan 19, 2023

What about --external:module? Documentation: https://esbuild.github.io/api/#external

@elefeint
Copy link
Author

This worked perfectly! This was our exact use-case; I missed it when reading the docs.

a package may contain code that only runs in node but you will only be using that package in the browser

Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants