babel / babel

🐠 Babel is a compiler for writing next generation JavaScript.
https://babel.dev
MIT License
43.2k stars 5.64k forks source link

@babel/highlight should evaluate if color should be forced each time highlight is called #12442

Open jaydenseric opened 3 years ago

jaydenseric commented 3 years ago

Bug Report

@babel/highlight should evaluate if color should be forced each time the highlight function is called, instead of only once when the module is loaded.

Current behavior

@babel/highlight evaluates if color should be forced once; when the module is loaded. Changing the value of process.env.FORCE_COLOR at runtime has no effect on @babel/code-frame output.

Expected behavior

@babel/highlight should evaluate if color should be forced each time the highlight function is called. Changing the value of process.env.FORCE_COLOR at runtime should have an effect on @babel/code-frame output.

Environment

Possible Solution

The problem is that a static supportsColor value that chalk defines once when the module loads is used here:

https://github.com/babel/babel/blob/c6aea4e85d2b8f3e82575642d30b01c8cbe112a9/packages/babel-highlight/src/index.js#L98-L103

chalk uses supports-color to determine this value, here:

https://github.com/chalk/chalk/blob/02abeebac3fa41b346ad1f0b4674d371953da932/source/index.js#L3

supports-color exports a supportsColor function so this value could be determined on demand, using:

require('supports-color').supportsColor(process.stdout);

Additional context

In a published package I author, I’m trying to do snapshot testing of the error messages a function throws that contains fancy colorized syntax highlighting, etc. using @babel/code-frame, which in turn uses @babel/highlight under the hood. The problem is, when I run npm test locally in a terminal the snapshot contains colors, but in GitHub actions CI the snapshots fail because there are no colors.

Typically in a situation like this before each snapshot test runs you could store the current process.env.FORCE_COLOR value, set it to 1, run the snapshot test with color forced, then afterwards restore the process.env.FORCE_COLOR value back to what it was.

Unfortunately due to this issue, changing process.env.FORCE_COLOR at runtime makes no difference when the @babel/code-frame function codeFrameColumns is called, in turn calling the @babel/highlight function highlight.

babel-bot commented 3 years ago

Hey @jaydenseric! We really appreciate you taking the time to report an issue. The collaborators on this project attempt to help as many people as possible, but we're a limited number of volunteers, so it's possible this won't be addressed swiftly.

If you need any help, or just have general Babel or JavaScript questions, we have a vibrant Slack community that typically always has someone willing to help. You can sign-up here for an invite."