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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parcel is replacing require with undefined in some cases that result in a runtime error #9522

Open
natan-stripe opened this issue Feb 6, 2024 · 0 comments

Comments

@natan-stripe
Copy link

natan-stripe commented Feb 6, 2024

馃悰 bug report

Hi there!

I'm running into an issue where Parcel's JavaScript transformer is replacing require in output bundles in ways that is causing a runtime error.

It looks like this might be intentional behavior (#6260) that was added for compatibility with Browserify but it seems like it's maybe not working properly in this case.

馃帥 Configuration (.babelrc, package.json, cli command)

Here's a repository setup with reproduction steps: https://github.com/natan-stripe/parcel-undefined-require/tree/main

Given input like this:

var dep;

if (require) {
    dep = require("./dep");
}

if (dep) {
    dep();
}

馃 Expected Behavior

I'd expected transformed output like this:

function(require,module,exports) {
  var dep;
  if (require) dep = require("22974921420fda43");
  if (dep) dep();
}

馃槸 Current Behavior

Instead we get transformed output like this:

function(require,module,exports) {
  var dep;
  if (undefined) dep = require("22974921420fda43");
  if (dep) dep();
}

The issue is really the undefined there on the 3rd line.

馃拋 Possible Solution

I think probably the bug is coming from some of the logic here: https://github.com/parcel-bundler/parcel/blob/v2/packages/transformers/js/core/src/dependency_collector.rs#L695-L719 but I'm extremely unfamiliar with the rust code in the JavaScript transformer.

馃敠 Context

This is causing an issue in one of our applications that has a dependency on dagre-d3, which basically structure all of its exported modules like this: https://unpkg.com/dagre-d3@0.6.1/lib/dagre.js

/* global window */

var dagre;

if (require) {
  try {
    dagre = require("dagre");
  } catch (e) {}
}

if (!dagre) {
  dagre = window.dagre;
}

module.exports = dagre;

The way this manifests is that, at runtime, any code attempting to reference one of these modules (dagre in this case) will instead resolve to undefined.

馃捇 Code Sample

https://github.com/natan-stripe/parcel-undefined-require/tree/main

馃實 Your Environment

Software Version(s)
Parcel 2.11.0 (it also manifests in older versions)
Node v18.14.0
npm/Yarn 1.22.19
Operating System OSX
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

1 participant