react/packages/react-devtools/preload.js
Brendan Abbott 0a7dc1b1c7
[devtools] Introduce REACT_DEVTOOLS_PORT for the standalone react-devtools (#30767)
## Summary

This PR attempts to make running the React DevTools a little friendlier
in projects that are not completely React.

At the moment, running the DevTools with `npx react-devtools` will
default to the port to use the `PORT` env variable otherwise it'll fall
back to `8097`. `PORT` is a common env variable, so we can get into this
strange situation where the a Rails server (eg Puma) is using `PORT`,
and then the React DevTools attempts to boot using the same `PORT`.

This PR introduces a dedicated env variable, `REACT_DEVTOOLS_PORT` to
assist in this scenario.

## How did you test this change?

I'm using fish shell, so I did the following, please let me know if
there's a better way:

```sh
cd packages/react-devtools
set -x PORT 1000
set -x REACT_DEVTOOLS_PORT 2000
node bin.js
```

We can see in the UI that it's listening on `2000`. Without this PR,
it'd listen on `1000`:

![Screenshot 2024-08-21 at 10 45
42 AM](https://github.com/user-attachments/assets/a5c7590c-1b54-4ac8-9a8b-8eb66ff67cfb)
2025-02-11 18:14:43 +00:00

42 lines
1.2 KiB
JavaScript

const {clipboard, shell, contextBridge} = require('electron');
const fs = require('fs');
const internalIP = require('internal-ip');
// Expose protected methods so that render process does not need unsafe node integration
contextBridge.exposeInMainWorld('api', {
electron: {clipboard, shell},
ip: {address: internalIP.v4.sync},
getDevTools() {
let devtools;
try {
devtools = require('react-devtools-core/standalone').default;
} catch (err) {
alert(
err.toString() +
'\n\nDid you run `yarn` and `yarn run build` in packages/react-devtools-core?',
);
}
return devtools;
},
readEnv() {
let options;
let useHttps = false;
try {
if (process.env.KEY && process.env.CERT) {
options = {
key: fs.readFileSync(process.env.KEY),
cert: fs.readFileSync(process.env.CERT),
};
useHttps = true;
}
} catch (err) {
console.error('Failed to process SSL options - ', err);
options = undefined;
}
const host = process.env.HOST || 'localhost';
const protocol = useHttps ? 'https' : 'http';
const port = +process.env.REACT_DEVTOOLS_PORT || +process.env.PORT || 8097;
return {options, useHttps, host, protocol, port};
},
});