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

Conditional require produces invalid output #8143

Closed
ross-pfahler opened this issue May 25, 2022 · 3 comments 路 Fixed by #8151
Closed

Conditional require produces invalid output #8143

ross-pfahler opened this issue May 25, 2022 · 3 comments 路 Fixed by #8151

Comments

@ross-pfahler
Copy link

馃悰 bug report

When conditionally loading css via commonjs the resulting code is invalid.

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

Parcel with no .parcelrc

馃 Expected Behavior

Code should compile without error.

馃槸 Current Behavior

The output code is invalid, which causes Terser to throw an unexpected token error (see Code Sample)

馃拋 Possible Solution

Not sure!

馃敠 Context

I'm trying to load a library that conditionally includes CSS based on a environment variable

馃捇 Code Sample

Full repro at https://github.com/ross-pfahler/parcel-2-demos/tree/require-condition using yarn build --no-optimize

if (process.env.a) {
  require('./a.css');
} else {
  require('./b.css');
}

turns into:

if (undefined) {};
else {};

馃實 Your Environment

Software Version(s)
Parcel 2.6
Node 16
npm/Yarn yarn
Operating System osx
@101arrowz
Copy link
Member

101arrowz commented May 26, 2022

This is a limitation of our CSS packaging strategy that I anticipate will be very difficult to resolve. Conditional CSS implies loading the CSS only when a branch is taken, but to do it synchronously you'd have to download both CSS files in advance and only apply them when their branch is taken.

Also note that Parcel's strategy for process.env replacement is kind of cheating in that it just replaces with the actual value and lets Terser do the dead code elimination, so we can't currently statically determine which CSS file needs to be used. Actually for this case it should be fine and is a bug.

Is there a practical use case for this? If you really need this functionality you can just do:

const aCSS= require("bundle-text:./a.css")
if (branch) {
  const style = document.createElement('style');
  style.innerText = aCSS;
  document.head.appendChild(style);
}

(Though even that is blocked by #7941).

@mischnic
Copy link
Member

No, we actually run swc'a DCE in the transformer before we collect all of the require calls (for exactly this usecase).
Some recent swc upgrade might has broken this

@101arrowz
Copy link
Member

Oh OK, does SWC's DCE work the same as Terser? Sorry for the bad info!

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

Successfully merging a pull request may close this issue.

3 participants