The answer provided by tpdietz is a very good one and would probably work well for many libraries.
However, this specific library I'm trying to use (Rollbar) needs to be loaded before any other JavaScript (e.g. React and ReactDOM), or else it can't capture all errors. Since those other libraries are loaded via import
statements, I can't use a require
statement in front of them at the top of index.js
.
The solution I found (thanks to GitHub user rokob with the Rollbar.js project) is to reference the NODE_ENV
variable from within the index.html
file, as described here: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#referencing-environment-variables-in-the-html
At the top of my index.html
file, in a <script>
tag, I can set a variable to %NODE_ENV%
. The build process for create-react-app will automatically parse that variable and insert the name of the environment, e.g. "production" or "development", in the final index.html
file. Then, I can check to see if that variable is equal to "production" before executing any inline JavaScript.
Example index.html
:
<!doctype html>
<html lang="en">
<head>
<script>
var environment = "%NODE_ENV%";
if (environment === "production") {
// code here will only run when index.html is built in production environment
// e.g. > $ NODE_ENV="production" npm run build
}
</script>
In the specific case of Rollbar.js, I just needed to pass a config parameter with the environment name, so no if
statement is necessary:
var _rollbarConfig = {
...
enabled: ('%NODE_ENV%' === 'production') //returns true if 'production'
...
};
Here is the issue on Github where rokob gave me this solution: https://github.com/rollbar/rollbar.js/issues/583